ggplot:从几年的子集中添加新行 [英] ggplot: adding new lines from a subset of years

查看:53
本文介绍了ggplot:从几年的子集中添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约90年的每日数据,我想绘出长期平均值,以及调查期间(2014-2018年)每年的单行.数据如下:

I have about 90 years of daily data and I want to plot the long term mean, plus the individual lines for each year of my survey period (2014-2018). The data looks like this:

> head(dischg)
      date   ddmm year cfs      daymo
1 1-Jan-27 01-Jan 1927 715 2018-01-01
2 2-Jan-27 02-Jan 1927 697 2018-01-02
3 3-Jan-27 03-Jan 1927 715 2018-01-03
4 4-Jan-27 04-Jan 1927 796 2018-01-04
5 5-Jan-27 05-Jan 1927 825 2018-01-05
6 6-Jan-27 06-Jan 1927 865 2018-01-06

我已经能够很容易地绘制长期均值:

I have been able to plot the long term mean easily enough:

p1 <- ggplot(dischg, aes(x=daymo, y=cfs)) +
  stat_summary(fun.data = "mean_cl_boot", geom = "smooth", colour = "blue")  

...但是我需要一些帮助来绘制年份的子集.我尝试使用子集"

... but I need some help plotting the subset of years. I tried using "subset"

p2 <- p1 +
  ggplot (subset(dischg, year %in% c(2014:2018)), aes(x=daymo, y=cfs, linetype=year)) +
  geom_line() +
  scale_colour_brewer(palette="Set1") 

但我收到此错误:

错误:不知道如何在绘图中添加o

Error: Don't know how to add o to a plot

一次只增加一年会更聪明吗?当要绘制五年的数据时,这似乎有点麻烦.

Would it be smarter to just add one year at a time? That seems a bit cumbersome when there are five years of data to plot.

推荐答案

感谢您提供示例数据,但是很遗憾,我无法让 ggplot 代码与您提供的示例数据一起运行,所以我将使用内置的R数据集.但是,这些概念是相同的.

Thank you for providing sample data, however, I unfortunately cannot get the ggplot code to run with that sample data you provided so I will use a built in R dataset. The concepts are the same though.

问题是您正在尝试将 ggplot 添加到已经是 ggplot 类的对象中.将对象初始化为 ggplot 对象后,无需每次要添加图层时都调用 ggplot .例如,如果尝试,我将得到与您相同的错误:

The issue is that you are trying to add ggplot to an object that is already of class ggplot. Once you have initialized your object as a ggplot object, you don't need to call ggplot each time you want to add a layer. For example, I get the same error you do if I try:

p1 <- ggplot(mtcars, aes(x=hp,y=cyl)) + geom_point()
p2 <- p1 + ggplot(mtcars[mtcars$am == 1, ], aes(x = hp, y = cyl)) + geom_line()

正如我的评论中所述,如果要添加包含单独数据的另一层(在您的情况下为 geom_line ),可以通过将数据直接放入 geom _ 调用.在您的情况下,您将执行以下操作:

As mentioned in my comment, if you want to add another layer with separate data (in your case the geom_line) you can do this by putting the data directly into the geom_ call. In your case you would do something like:

p1 <- ggplot(mtcars, aes(x=hp,y=cyl)) + geom_point()
p2 <- p1 + geom_line(data = mtcars[mtcars$am == 1, ])

p2

这篇关于ggplot:从几年的子集中添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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