R语言 使用position =“dodge”的比例标签制作ggplot条形图

toiithl6  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(133)

我有一个数据集:

structure(list(X = 1:6, lake = c("x", "x", "y", "y", "z", "z"
), harv = c(27351.4588, 83303.21336, 32258.14338, 64784.5816, 
107123.759, 85215.79412), prop2 = c(24.7, 75.3, 33.2, 66.8, 55.7, 
44.3), variable = structure(c(2L, 1L, 2L, 1L, 2L, 1L), levels = c("User", 
"Non-User"), class = "factor")), row.names = c(NA, -6L), class = "data.frame")

我想做一个情节:

ggplot(df,aes(x=lake,y=harv))+
geom_bar(aes(fill=variable),stat="identity",position = position_dodge2(width=0.9))+  
geom_text(size=7,aes(x=lake, y=harv, label = paste0(round(prop2,digits = 2),"%"),
vjust=-0.5), position = position_dodge2(width=0.9))

为什么我的比例标签会出现在错误的列中?当变量不是因子但我希望条形图保持为因子设置的顺序时,它有效。

vhmi4jdf

vhmi4jdf1#

我们可以使用geom_col()

library(ggplot2)

ggplot(df,aes(x=lake,y=harv, fill=variable))+
  geom_col(position = position_dodge2(width=0.9))+
  geom_text(size=7,aes(x=lake, y=harv, label = paste0(round(prop2,digits = 2),"%"),
                       vjust=-0.5), position = position_dodge2(width=0.9))

相关问题