简体   繁体   English

R ggplot stat_summary:如何在图例中包括NA数量?

[英]R ggplot stat_summary: how to include a count of NAs in legend?

I am trying to plot one discrete variable on the x-axis against a continuous one on the y. 我试图在x轴上绘制一个离散变量,而在y上绘制一个连续变量。 Imagine in mtcars that I am trying to plot cyl vs. disp. 想象一下在mtcars中我试图绘制cyl vs. disp。 What if some of the values of disp were NA? 如果disp的某些值是NA怎么办? I would like to know how many NA there were for each value of cyl, and to display this in a simple table, possibly right below the legend (or within the legend itself). 我想知道cyl的每个值有多少个NA,并将其显示在一个简单的表中,可能在图例的正下方(或图例本身内)。 Is there a simple (or a complicated) way to do this? 有没有简单(或复杂)的方法来做到这一点?

Similar and related question I posed: R - looking at means by subgroup and overall on a line graph 我提出的类似且相关的问题: R-在折线图上按子组和整体查看均值

Thanks! 谢谢!

This answer does not meet all question requirements, but since the details on how exactly the data should be presented are a little vague, I'm posting anyway. 这个答案并不能满足所有问题的要求,但是由于有关如何准确显示数据的细节有些含糊,所以我还是在发布。

So here's a way to add NA counts to the legend itself: 因此,这是一种将NA计数添加到图例本身的方法:

library(datasets)
mycars <- mtcars
mycars$disp[c(1,2,3)] <- NA

lvls = levels(as.factor(mycars$cyl))
nacounts <- by(mycars, mycars$cyl, function(x) sum(is.na(x$disp)))
labels = paste(lvls," (NA=",as.integer(nacounts),")",sep="")

ggplot(data=mycars) +
   geom_boxplot(aes(x=cyl,y=disp, fill=as.factor(cyl)))  +
   scale_fill_discrete(name="Cyl", labels=labels)

结果

EDIT 编辑

Relating to the stat_summary graph referred-to in the question: labels describing line types can be added using the scale_linetype_* functions. 关于问题中提到的stat_summary图:可以使用scale_linetype_ *函数添加描述线型的标签。

In case you'd like to have the same legend as in the image above, I think you'll have to add graph elements describing cyl, eg: 如果您希望使用与上图相同的图例,我认为您必须添加描述cyl的图形元素,例如:

ggplot(mycars,aes(cyl,disp)) +
  stat_summary(fun.y=mean, geom="line", lwd=1.5) +
  stat_summary(aes(lty=factor(vs)),fun.y="mean",geom="line") +
  stat_summary(aes(color=factor(cyl)),fun.y="mean",geom="point",size=5) +
  scale_x_continuous(breaks=c(4,6,8),labels=c("four","6","8")) +
  scale_color_discrete(labels=labels)

点几何叠加的绘图

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

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