r - 无法使用 ggplot2 绘制多线图

标签 r dataframe ggplot2 dplyr

我有一个数据集,其中有一列是失业率,一列是月份,一列是年份。

我想做一个线图,其中 x 轴为月份数,y 轴为失业率,每条线代表不同的年份。

我首先按年份过滤数据帧,分别获取每年的 y 值,然后尝试了以下代码:

y1 = df %>% filter(year == 1996) 
y1 = y1$unemploy
y2 = df %>% filter(year == 1997)
y2 = y2$unemploy
y3 = df %>% filter(year == 1998)
y3 = y3$unemploy 

plot1 = ggplot() +  
  geom_line(mapping = aes(x = df$month, y = y1), color = "navyblue") +
  geom_line(mapping = aes(x = df$month,y = y2), color = "black") +
  geom_line(mapping = aes(x = df$month,y = y3), color = "red") +
  scale_y_continuous(limits=c(0,10)) +
  scale_x_continuous(limits=c(1,15)) 
plot1

但是当我尝试打印该图时,我收到以下错误消息:

Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (128): y
Run `rlang::last_error()` to see where the error occurred.

有谁知道这个情节可能有什么问题吗?

dput(head(df,20)) 的输出如下:

dput(head(df, 20))
structure(list(unemploy = c(6.7, 6.7, 6.4, 5.9, 5.2, 4.8, 4.8, 
4, 4.2, 4.4, 5, 5, 6.4, 6.5, 6.3, 5.9, 4.9, 4.8, 4.5, 4), month = c(1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 
5L, 6L, 7L, 8L), year = c(1996L, 1996L, 1996L, 1996L, 1996L, 
1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1997L, 1997L, 
1997L, 1997L, 1997L, 1997L, 1997L, 1997L)), row.names = c(NA, 
20L), class = "data.frame")

最佳答案

对于您使用的方法,您需要为每个几何对象使用不同的数据集;您将 df 中变量 month 的所有行分配给 x,仅将 unemploy 列的一个子集分配给 y,因此,不同数量的ggplot 中的 x 和 y 实体返回错误。

y1 = df %>% filter(year == 1996) 

y2 = df %>% filter(year == 1997)

y3 = df %>% filter(year == 1998)


plot1 = ggplot() +  
  geom_line(y1, aes(x = month, y = unemploy), color = "navyblue") +
  geom_line(y2, aes(x = month, y = unemploy), color = "black") +
  geom_line(y3, aes(x = month, y = unemploy), color = "red") +
  scale_y_continuous(limits=c(0,10)) +
  scale_x_continuous(limits=c(1,15)) 
plot1

但更好的做法是在映射中使用颜色:

df %>%
  filter(year %in% c("1996", "1997", "1998")) %>%
ggplot() +  
  geom_line(aes(x = month, y = unemploy, color = year)) +
  scale_y_continuous(limits=c(0,10)) +
  scale_x_continuous(limits=c(1,15)) 

如果您想要这些特定颜色并且不喜欢默认的 ggplot 颜色,您可以稍后使用 scale_color_manual

关于r - 无法使用 ggplot2 绘制多线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74426581/

相关文章:

r - 查找数据框每一列的最后一行

r - 在子数据集的图之间创建通用图例

r - ggplot2:当 'size' 包含内部和外部 aes 语句时,为什么符号大小不同?

r - 访问带引号的点参数的名称

dplyr 中的回归输出

r - 如何在旧的、不兼容的 R 版本上安装新的 R 包

r - 如何通过对 R 中的变量进行分组来为折线图着色?

r - R 图中条的边缘宽度

python 将每小时数据 [1-24] 添加到日期时间数据

r - 计算 R 中每一列的出现次数