我正在尝试创建以下数据框的条形图:
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"
))
我正在尝试使用以下命令创建躲避的条形图:
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))
但是由于某些原因,测试不是躲避而是堆叠-尽管有特定的位置要求。
有什么想法吗?
答案 0 :(得分:2)
您只需要使用fill参数指定条形代表什么。否则,ggplot不知道将文本放置在何处。 这样可以解决您的问题吗?
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))
您可能还会看到以下问题:Position geom_text on dodged barplot