简体   繁体   English

stat_summary() 和 fun.data = mean_sdl 不起作用

[英]stat_summary() and fun.data = mean_sdl not working

set.seed(1) # generate random data
day1 = rnorm(20,0,1)
day2 = rnorm(20,5,1)
Subject <- rep(paste0('S',seq(1:20)), 2)
Data <- data.frame(Value = matrix(c(day1,day2),ncol=1))
Day <- rep(c('Day 1', 'Day 2'), each = length(day1))
df <- cbind(Subject, Data, Day)

Using this random data, I'd like to plot individual points with unique color for each subject and a summary point (mean + standard deviation).使用此随机数据,我想为每个主题绘制具有独特颜色的单个点和一个汇总点(平均值 + 标准偏差)。

It seems that the plot is okay when all points are plotted with the same color because stat_summary(fun.data = mean_sdl) works properly.当所有点都用相同的颜色绘制时,这个图似乎没问题,因为stat_summary(fun.data = mean_sdl)工作正常。

ggplot(data = df, mapping = aes(x= Day, y =Value)) +
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 2),
               geom = 'pointrange', fatten = 3*1.2, size = 1.2,
               color= 'black')  +
  geom_point(size = 2) 

在此处输入图片说明 But not when all points have unique color (for each subject).但不是当所有点都具有独特的颜色时(对于每个主题)。

ggplot(data = df, mapping = aes(x = Day, y = Value,
                                fill = Subject)) +
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 2),
               geom = 'pointrange', fatten = 3*1.2, size = 1.2,
               color = 'black') +
  geom_point(shape = 21, color = 'white', size = 2) 

在此处输入图片说明

In your example ggplot assumes that each color corresponds to an individual group, but you want the grouping and color to be separate.在您的示例 ggplot 假设每种颜色对应于一个单独的组,但您希望分组和颜色分开。 Therefore, you need to explicitly define the group to be "Day".因此,您需要将组明确定义为“Day”。

ggplot(data = df, mapping = aes(x = Day, y = Value,
                                fill = Subject, group = Day)) +
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 2),
               geom = 'pointrange', fatten = 3*1.2, size = 1.2,
               color = 'black') +
  geom_point(shape = 21, color = 'white', size = 2) 

在此处输入图片说明

Try the following:请尝试以下操作:

ggplot(data = df, mapping = aes(x= Day, y =Value)) +
  stat_summary(fun.data = mean_sdl, fun.args = list(mult = 2),
               geom = 'pointrange', fatten = 3*1.2, size = 1.2,
               color= 'black')  +
  geom_point(size = 2, aes(color = Subject)) 

Instead of specifying fill in aes() in the first line ( ggplot(...) ), I've moved it to the geom_point() element instead.我没有在第一行( ggplot(...) )中指定fill aes() ,而是将它移到geom_point()元素。 Otherwise, stat_summary() will be doing its calculations grouped using Subject !否则, stat_summary()将使用Subject分组计算!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM