【问题标题】:Stat summary for each factor in scatter plot ggplot2: What about fun.x, fun_y combinations?散点图中每个因素的统计摘要 ggplot2:fun.x、fun_y 组合怎么样?
【发布时间】:2019-05-21 22:19:44
【问题描述】:

我有一堆关于人们接触细菌最多 5 次的数据。我正在比较戴手套和不戴手套的拾取量。我想通过因子 NumberContacts 绘制平均值并将其涂成红色。例如。下图中的红点。

到目前为止我有:

require(tidyverse)
require(reshape2)

制作一些数据

    df<-data.frame(Yes=rnorm(n=100),
No=rnorm(n=100),
NumberContacts=factor(rep(1:5, each=20)))

计算每个组的平均值= NumberContacts

centroids<-aggregate(data=melt(df,id.vars ="NumberContacts"),value~NumberContacts+variable,mean)

将它们分成两列

centYes<-subset(centroids, variable=="Yes",select=c("NumberContacts","value"))
centNo<-subset(centroids, variable=="No",select="value")
centroids<-cbind(centYes,centNo)
colnames(centroids)<-c("NumberContacts","Gloved","Ungloved")

制作一个丑陋的情节。

ggplot(df,aes(x=gloves,y=ungloved)+
  geom_point()+
  geom_abline(slope=1,linetype=2)+
  stat_ellipse(type="norm",linetype=2,level=0.975)+
  geom_point(data=centroids,size=5,color='red')+
  #stat_summary(fun.y="mean",colour="red")+ doesn't work
  facet_wrap(~NumberContacts,nrow=2)+
  theme_classic()

有没有更优雅的方式使用 stat_summary?另外,如何更改图表顶部框的外观?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    stat_summary 不是一个选项,因为(请参阅?stat_summary):

    stat_summary 在unique x

    上运行

    也就是说,虽然我们可以取 y 的平均值,但 x 保持不变。但是我们可能会做一些非常简洁的事情:

    ggplot(df, aes(x = Yes, y = No, group = NumberContacts)) +
      geom_point() + geom_abline(slope = 1, linetype = 2)+
      stat_ellipse(type = "norm", linetype = 2, level = 0.975)+
      geom_point(data = df %>% group_by(NumberContacts) %>% summarise_all(mean), size = 5, color = "red")+ 
      facet_wrap(~ NumberContacts, nrow = 2) + theme_classic() + 
      theme(strip.background = element_rect(fill = "black"),
            strip.text = element_text(color = "white"))
    

    这也表明要修改上面的框你要查看strip elementstheme

    【讨论】:

    • 谢谢,有道理!已经有了黑色上衣,图表看起来更好。
    猜你喜欢
    • 1970-01-01
    • 2014-12-22
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多