Reputation: 1190
I have some data where some groups do not appear on all months. I am plotting this on a bar graph but with a text label showing the numerical values but the text are not seating on top of each bar. I tried using the position "dodge" for the labels but with no success.
Below is a reproducible example:
library(ggplot2)
library(dplyr)
library(scales)
data.frame(Month = as.Date(c("2015-01-01", "2015-01-01","2015-01-01",
"2015-02-01","2015-02-01","2015-02-01")),
types = rep(LETTERS[1:3],2),
percent = c(0.2,NA,NA,.39,.89,.59)) %>%
ggplot( aes(x = Month, y = percent, fill = types)) +
geom_bar(stat = "identity", position = "dodge") +
scale_y_continuous(labels = percent) +
scale_x_date(labels = date_format("%Y-%b")) +
geom_text(stat = 'identity',
aes(label = ifelse(percent > .02,
paste(round(percent*100,0),"%",sep = "") ,'')))
This is what it looks like:
Upvotes: 0
Views: 1541
Reputation: 7800
A couple suggestions,
lubridate
for working with datesMonths
to a factor variable. This will help when using position_dodge()
.Try using the code below. If you have more than one year of data you may consider constructing the month factor variable with the year appended to the month.
library(ggplot2)
library(dplyr)
library(scales)
library(lubridate)
data.frame(Month = months(ymd(c("2015-01-01", "2015-01-01","2015-01-01", "2015-02-01","2015-02-01","2015-02-01"))),
types = rep(LETTERS[1:3],2),
percent = c(0.2,NA,NA,.39,.89,.59)) %>%
mutate(Month = factor(Month, levels = month.name),
label = ifelse(!is.na(percent), paste0(round(percent*100), "%"), "")) %>%
ggplot() +
aes(x = Month, y = percent, fill = types) +
geom_bar(stat = "identity", position = position_dodge(w = 0.75)) +
geom_text(position = position_dodge(w = 0.75),
aes(ymax = percent, label = label))
Upvotes: 1