stat_summary无法识别aes()

2sbarzqh  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(121)

你好,我想用stat_summary函数为每个彩色组绘制新浪图:

library(ggplot2)
library(ggforce)
    ggplot(diamonds |>  filter(cut=="Fair"), aes(x=cut, y=price, color=clarity )) + 
        scale_color_brewer(palette = "Dark2", guide = "none")+ 
        geom_violin(fill = "gray80", linewidth = 1, alpha = .5) +
        geom_sina(alpha = .25) +
        coord_flip()+
        stat_summary(fun.data = "mean_se", colour = "black", linewidth = 1, size = 0.5)

但不知何故stat_summary不能识别aes(),所以我只得到一个平均值(黑点)。我如何使它对每个组都是这样?x1c 0d1x
我试过group=interaction(cut, clarity)-但它仍然不是我要找的东西。

tzdcorbm

tzdcorbm1#

只需将group = clarity放入stat_summaryaes中。您还需要添加position_dodge

ggplot(diamonds |>  filter(cut=="Fair"), 
       aes(x=cut, y=price, color=clarity )) + 
  scale_color_brewer(palette = "Dark2", guide = "none")+ 
  geom_violin(fill = "gray80", linewidth = 1, alpha = .5) +
  geom_sina(alpha = .25) +
  coord_flip()+
  stat_summary(fun.data = "mean_se", colour = "black", 
               linewidth = 1, size = 0.5, aes(group = clarity),
               position = position_dodge(0.9))

wgx48brx

wgx48brx2#

问题是你把x轴设置为cut,当你真的希望它由clarity来设置的时候。对于小提琴图,它会错开它们来显示点,但是stat_summary不起作用。如果你设置了x=clarity,那么所有的图元素都会被x-axis组正确地设置:

library(ggplot2)
library(ggforce)
ggplot(diamonds |> dplyr::filter(cut=="Fair"), aes(x=clarity, y=price, color=clarity )) + 
    scale_color_brewer(palette = "Dark2", guide = "none")+ 
    geom_violin(fill = "gray80", linewidth = 1, alpha = .5) +
    geom_sina(alpha = .25) +
    coord_flip()+
    stat_summary(fun.data = "mean_se", color = 'black', linewidth = 1, size = 0.5, )

相关问题