【问题标题】:R | ggplot2 | bar in barplot does not start at the right value右 | ggplot2 | barplot 中的 bar 没有从正确的值开始
【发布时间】:2021-04-30 16:15:13
【问题描述】:

我想可视化我使用 ggplot2 使用两个程序“kosmic”和“RLE”计算的几种肝酶(例如 GOT 和 GPT)的参考范围。

我不明白为什么条形图总是从 0 开始,即使较低的范围是例如 16.02。

我需要如何更改我的代码,使条形图的最小值和最大值如下所示:

[16.02,45.46] [9.16,60.52] [16.10,68.9​​0] 和 [9.30,64.40]。

提前谢谢你!

#install.packages("ggplot2")

library(ggplot2)


program <- c(rep("kosmic",4),rep("RLE",4))

value <- c(16.02,45.46,9.16,60.52,16.1,48.9,9.3,64.4)


parameter <- c(rep("GOT",2),rep("GPT",2),rep("GOT",2),rep("GPT",2))

table1 <- data.frame(program,value,parameter)


p <- ggplot(table1, aes(parameter,value, fill = program))+
        geom_bar(position="dodge", stat="identity")
        

print(p)

我正在寻找这样的东西:

【问题讨论】:

  • 对于每个程序参数组合,您有两个观察结果,并且它正在堆叠它们。您希望它看起来如何?
  • 像这样:imgur.com/a/eq2Le34

标签: r ggplot2 plot bar-chart


【解决方案1】:

你在寻找这样的东西吗?

library(dplyr)
table1 %>%
  group_by(parameter, program) %>%
  summarize(min = min(value), 
            median = median(value),
            max = max(value), .groups = "drop") %>%
ggplot(aes(interaction(parameter,program), fill = program))+
  geom_tile(aes(y = median, height = max-min), width = 0.6)

编辑: 好的,这很老套,但是:

table1 %>%

 # example of reordering the parameters
 mutate(parameter = fct_relevel(parameter, "GPT", after = 0)) %>%
  # forcats offers a variety of fct_*** functions to change factors
  # (factors are a data type that can separately store labels and ordering)

  group_by(parameter, program) %>%
  summarize(min = min(value), 
            median = median(value),
            mean = mean(value),
            max = max(value), .groups = "drop") %>%
  ggplot(aes(parameter, mean, color = program))+
  geom_errorbar(aes(ymin = min, ymax = max), 
                position = position_dodge(width = 0.3), size = 10,
                width = 0) + 

  # control the legend so the key squares aren't gigantic to match the error bar widths
  guides(colour = guide_legend(override.aes = list(size=8))) +

  # example of assigning different colors. 
  # a variety of scale_color_* functions are available
  scale_color_manual(values = c("kosmic" = "#cc5588", "RLE" = "#779988"))

这样做的一个缺点是,条形的宽度/间距会根据您的图形输出纵横比而有所不同,因此要使用它可能需要一些摆弄才能得到想要的结果。

【讨论】:

  • 酷!我认为OP正在寻找这个。点赞!
  • 谢谢,但我正在寻找这样的东西:imgur.com/a/eq2Le34
  • 嗯。我不知道在 ggplot2 中执行此操作的明显方法,因为 geom_bar/geom_col 几何构造的基线为零,但据我所知 geom_tile 和 geom_rect 并没有相同的方便躲避语法。所以我认为你需要伪造它,例如通过在你想要的下面制作透明的 geom_cols,或者强制 geom_tile/rect 的间距。
  • 感谢乔恩!不是所有的英雄都穿斗篷
  • 如何手动更改条的颜色?以及如何更改参数的顺序?因为现在它们按字母顺序串在一起。
【解决方案2】:

根据您的需要,我建议使用箱形图而不是条形图:

ggplot(table1, aes(x = parameter, y = value, fill = program, color = program)) +
    geom_point(position = position_jitterdodge()) + 
    geom_boxplot(outlier.shape = NA, color = 'black') 

【讨论】:

  • 谢谢,但 Jon 发布的正是我想要的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 2021-10-15
  • 1970-01-01
  • 2013-01-11
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多