Reputation: 2443
I am trying to create a bar plot of the following data frame:
df <- structure(list(HCT_range = c("Low", "Low", "Low", "Low", "Low",
"Low"), HG1_range = c("High", "High", "Normal", "High", "High",
"Normal"), HG2_range = c("High", "Normal", "High", "High", "Normal",
"High"), n = c(17L, 54L, 66L, 15L, 61L, 60L), Type = c("LHH",
"LHN", "LNH", "LHH", "LHN", "LNH"), File = c("a", "a", "a", "b",
"b", "b"), Perc = c(0.0387, 0.123, 0.1503, 0.0342, 0.1389, 0.1366
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))
I am trying to create a dodged bar plot with the following command:
ggplot(data = df, aes(x = Type, y = n)) +
geom_col(aes(fill = File), position = position_dodge(width = 0.9)) +
geom_text(aes(label = Perc), position = position_dodge(0.9))
But for some reason, the test is not dodged but stacked - despite the specific position call.
Any ideas?
Upvotes: 0
Views: 2590
Reputation: 3
I was having trouble replicating alex_555's suggestion and eventually stumbled onto a fix: my x data was a date type, and I had to change the x to as.factor(Date) before it the geom_text would align properly.
ggplot(aes(x=as.factor(Date), y=Cost, fill=Legend)) +
geom_col(aes(fill=Legend),position=position_dodge(), alpha=.75) +
geom_text(aes(label=format(round(Cost), nsmall=0, big.mark=",")), size=4, position=position_dodge(width=.9), vjust=-0.3)
Upvotes: 0
Reputation: 1102
You just need to specify what your bars represent with the fill argument. Otherwise ggplot doesn't know where to place the text. Does this solve your problem?
ggplot(data = df, aes(x = Type, y = n, fill=File)) +
geom_col(aes(fill = File), position = position_dodge(width = 0.9)) +
geom_text(aes(label = Perc), position = position_dodge(0.9))
You may also have a look at this question: Position geom_text on dodged barplot
Upvotes: 4