我有一个数据集,其中有一列是失业率,一列是月份,一列是年份。
我想做一个线图,其中 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/