首页 > 解决方案 > ggplot中分组条形图的格式

问题描述

我目前坚持格式化分组条形图。

我有一个数据框,我想将其可视化:

  iteration  position value
1         1   eEP_SRO 20346
2         1 eEP_drift 22410
3         1  eEP_hole 29626
4         2   eEP_SRO 35884
5         2 eEP_drift 39424
6         2  eEP_hole 51491
7         3   eEP_SRO 51516
8         3 eEP_drift 55523
9         3  eEP_hole 74403

位置应显示为颜色,值应以条形高度表示。

我的代码是:

fig <- ggplot(df_eEP_Location_plot, aes(fill=position, y=value, x=iteration, order=position)) + 
  geom_bar(stat="identity")

这给了我这个结果:

在此处输入图像描述

我想有一个正确的 y 轴标签,并且还想将我的条从最大到最小排序(忽略迭代次数)。我怎样才能做到这一点?

非常感谢您的帮助!

标签: rggplot2plotformattingbar-chart

解决方案


我建议使用fct_reorderfrom the forcatspackage 在绘制之前沿指定值重新排序迭代ggplot。使用您提供的示例数据查看以下内容:

library(ggplot2)
library(forcats)
iteration <- factor(c(1,1,1,2,2,2,3,3,3))
position <- factor(rep(c("eEP_SRO","eEP_drift","eEP_hole")))
value <- c(20346,22410,29626,35884,39424,51491,51516,55523,74403)
df_eEP_Location_plot <- data.frame(iteration, position, value)
df_eEP_Location_plot$iteration <- fct_reorder(df_eEP_Location_plot$iteration, 
                                              -df_eEP_Location_plot$value)
fig <- ggplot(df_eEP_Location_plot, aes(y=value, x=iteration, fill=position)) + 
  geom_bar(stat="identity")
fig    

无花果


推荐阅读