【问题标题】:Formatting of grouped bar chart in ggplotggplot中分组条形图的格式
【发布时间】:2021-02-20 15:46:50
【问题描述】:

我目前正忙于格式化分组条形图。

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

  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 轴标签,并且还想要将我的条形从大到小排序(忽略迭代次数)。我怎样才能做到这一点?

非常感谢您的帮助!

【问题讨论】:

  • 请尝试以有用的格式共享数据,请参阅these reasons。对于 R,复制粘贴 dput(your_example_data) 的输出是首选方式。

标签: r ggplot2 plot formatting bar-chart


【解决方案1】:

我建议使用forcats 包中的fct_reorder 在绘制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    

【讨论】:

    猜你喜欢
    • 2013-08-12
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多