作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在过去 3 年中拥有多个数据源。数据是不连续的,并且在多个地方重叠。我想用不同的颜色绘制每个数据源的点,然后添加一条使用所有数据源的趋势线。包含的代码有一些示例数据和两个绘图示例。第一次调用 ggplot,为所有数据绘制一条趋势线。第二个 ggplot 调用,使用自己的趋势线以不同的颜色清楚地绘制每个源。
library(ggplot2)
the.data <- read.table( header=TRUE, sep=",",
text="source,year,value
S1,1976,56.98
S1,1977,55.26
S1,1978,68.83
S1,1979,59.70
S1,1980,57.58
S1,1981,61.54
S1,1982,48.65
S1,1983,53.45
S1,1984,45.95
S1,1985,51.95
S1,1986,51.85
S1,1987,54.55
S1,1988,51.61
S1,1989,52.24
S1,1990,49.28
S1,1991,57.33
S1,1992,51.28
S1,1993,55.07
S1,1994,50.88
S2,1993,54.90
S2,1994,51.20
S2,1995,52.10
S2,1996,51.40
S3,2002,57.95
S3,2003,47.95
S3,2004,48.15
S3,2005,37.80
S3,2006,56.96
S3,2007,48.91
S3,2008,44.00
S3,2009,45.35
S3,2010,49.40
S3,2011,51.19")
ggplot( the.data, aes( the.data$year, the.data$value ) ) + geom_point() + geom_smooth()
#ggplot( the.data, aes( the.data$year, the.data$value, color=the.data$source ) ) + geom_point() + geom_smooth()
第二个调用显示彩色数据点,我想添加一条代表所有年份的连续趋势线。
最佳答案
像这样:
ggplot(the.data, aes( x = year, y = value ) ) +
geom_point(aes(colour = source)) +
geom_smooth(aes(group = 1))
一些注意事项:
不要将美学映射到像 the.data$year
这样的孤立向量。 (直到您真正知道自己在做什么,并且知道何时打破该规则。)只需使用列名即可。
在各自的 geom
调用中将您想要的美学映射到单独的图层中。在这种情况下,我希望点的颜色不同,但对于平滑线,我希望将数据分组在一起 (group = 1
)。
关于r - 如何在 R 和 ggplot2 中获得具有多个数据集的单个趋势线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12810861/
我是一名优秀的程序员,十分优秀!