【问题标题】:How to make a grouped boxplot using 2 columns如何使用 2 列制作分组箱线图
【发布时间】:2021-08-09 17:41:26
【问题描述】:

我想制作一个箱线图如下: x 轴上:不同的组(健康、疾病 1、疾病 2) 在y轴上:大脑大小,以不同颜色并排显示“左脑大小”和“右脑大小”

我正在使用 ggplot 函数

data <- df[c("Group", "Left brain size", "Right brain size")]

ggplot(data, aes(x=Group ,y=..))+
  geom_boxplot()

我应该如何组织我的数据:x = Group,y = Brain size,fill = side?​​p>

谢谢! PS:我的数据示例如下表

Group Left brain size Right brain size
Healthy 0.5 0.9
Healthy 0.4 0.8
Healthy 0.8 0.4
Disease 1 0.7 0.5
Disease 1 0.9 0.3
Disease 1 0.2 0.1
Disease 2 0.3 0.8
Disease 2 0.4 0.54
Disease 2 0.1 0.4
Disease 2 0.3 0.2

【问题讨论】:

  • 您好,您可以使用 tidyr::pivot_longer() 来重塑您的数据以获得列“大脑大小”。它应该看起来像:tidyr::pivot_longer(df, cols = c("Left brain size", "Right brain size"), names_to = "side", values_to = "size")
  • 然后,像这样使用这个新的df:ggplot(data = df, aes(x = Group, y = size, fill = side)) + geom_...
  • 这能回答你的问题吗? Reshaping data to plot in R using ggplot2

标签: r ggplot2


【解决方案1】:

应该这样做:

df_ %>% 
  rename( # here we rename the columns so things look nice in the graph later
    Left = Left.brain.size,
    Right = Right.brain.size
  ) %>% 
  pivot_longer( # then we collapse the columns for each side of the brain into a single column, with a second column holding size values
    cols = c("Left", "Right"),
    names_to = "Side",
    values_to = "Size"
  ) %>% # then we plot and give it a title
  ggplot(
    aes(
      x = Group,
      y = Size,
      fill = Side
    )
  ) + 
  geom_boxplot() +
  labs(
    title = "Hemisphere Size by Group"
  )

这是输出:

这是你要找的吗?

【讨论】:

  • 这正是我想要的!它完美地工作。谢谢 ! PS:我还想使用 stat_boxplot 添加误差线,所以我必须更改误差线的位置以匹配框,这就是我所做的: stat_boxplot(geom = "errorbar", width = 0.5, position = position_dodge(宽度 = .75)) 再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 2020-05-22
相关资源
最近更新 更多