Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何使用两列创建分组箱线图_R_Ggplot2 - Fatal编程技术网

R 如何使用两列创建分组箱线图

R 如何使用两列创建分组箱线图,r,ggplot2,R,Ggplot2,我想做一个箱线图,如下所示: 在x轴上:不同的组(健康、疾病1、疾病2) 在y轴上:大脑大小,以不同的颜色并排显示“左脑大小”和“右脑大小” 我正在使用ggplot函数 data <- df[c("Group", "Left brain size", "Right brain size")] ggplot(data, aes(x=Group ,y=..))+ geom_boxplot() 数据这应该可以做到: df_ %&

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

我正在使用ggplot函数

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

ggplot(data, aes(x=Group ,y=..))+
  geom_boxplot()
数据这应该可以做到:

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"
  )
以下是输出:


这就是你要找的吗?

嗨,你可以通过使用,例如,
tidyr::pivot\u longer()
来重塑你的数据,得到一个柱状的“大脑大小”。它应该是这样的:
tidyr::pivot\u longer(df,cols=c(“左脑大小”,“右脑大小”),names\u to=“side”,values\u to=“size”)
然后,像这样使用这个新的df:
ggplot(data=df,aes(x=Group,y=size,fill=side))+geom…
。这回答了你的问题吗?那正是我想要的!它工作得很好。非常感谢。PS:我还想使用stat_boxplot添加错误条,因此我必须更改错误条的位置以匹配方框,这就是我所做的:stat_boxplot(geom=“errorbar”,width=0.5,position=position_dodge(width=0.75)),再次感谢!