ggplot2:连接分组数据手段的线 [英] ggplot2: line connecting the means of grouped data

查看:96
本文介绍了ggplot2:连接分组数据手段的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我的数据的一个变量与另一个变量分组,然后通过手段绘制一条线。当两个变量都是数字时,它工作正常。但是,当分组变量是一个因素时,我遇到了问题。下面我有一个模拟。
$ b

  x < -  sample(1:3,40,replace = T)
y < - rnorm(40 )

df1 < - data.frame(x,y)
qplot(x,y,data = df1)+ stat_summary(fun.y = mean,color =red, geom =line)



这看起来很棒。但是,如果x变量是一个因素,我没有得到该行。

pre $ df2 < - data.frame(x = as.factor(x),y​​)
qplot(x ,y,data = df2)+ stat_summary(fun.y = mean,color =red,geom =line)



有什么我可以做到这一行显示?



Ps。 geom =pointworks works but not geom =line

  qplot(x,y,data = df2)+ stat_summary fun.y = mean,color =red,geom =point)



感谢您阅读!!

解决方案

ggplot2 有意使得跨x轴系数画线是有点棘手的,因为你需要确保它有意义。如果你的X轴是纽约,费城和波士顿,绘制一条连接它们的线不是一个好主意。

然而,

然而, ,假设你的x变量有一个有意义的顺序,你必须定义 group 美学来绘制你想要的行。在这里, group = 1

  qplot(x,y,data = df2)+ 
stat_summary(fun.y = mean,color =red,geom =line,aes(group = 1))

如果您只需将 geom_line()添加到这样的图表中,您必须在一个图表中定义分组变量类似的方式。


I'm trying to group one variable of my data by another and then plot a line through the means. It works fine when both variables are numbers. However, I'm having a problem when the grouping variable is a factor. I have a mock up below.

x <- sample(1:3, 40, replace=T)
y <- rnorm(40)

df1 <- data.frame(x, y)
qplot(x, y, data=df1) + stat_summary(fun.y=mean, colour="red", geom="line")

This is looks great. However if the x variable is a factor I don't get the line.

df2 <- data.frame(x=as.factor(x), y)
qplot(x, y, data=df2) + stat_summary(fun.y=mean, colour="red", geom="line")

Is there something I can do to get this line displayed?

Ps. geom="point" works but not geom="line"

qplot(x, y, data=df2) + stat_summary(fun.y=mean, colour="red", geom="point")

Thanks for reading!!

解决方案

ggplot2 intentionally makes it a little tricky to draw lines across x-axis factors, because you need to make sure that it's meaningful. If your x-axis was "New York", "Philadelphia" and "Boston", it wouldn't be a good idea to draw a line connecting them.

However, assuming that your x variable has a meaningful order, you have to define the group aesthetic to draw the line you want. Here, group = 1.

qplot(x, y, data=df2) + 
  stat_summary(fun.y=mean, colour="red", geom="line", aes(group = 1))

If you just add geom_line() to a plot like this, you will have to define the grouping variable in a similar way.

这篇关于ggplot2:连接分组数据手段的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆