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?
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