在一张图中绘制不同的列R

时间:2019-03-14 19:03:15

标签: r ggplot2 plot ggplotly

我的样本数据:

structure(list(year = c(2018, 2018, 2018, 2018, 2019, 2019), 
    month = c(9, 10, 11, 12, 1, 2), pred1 = c(-6.63356483810535, 
    -6.50968293287978, -1.54767782423655, -1.47812226859267, 
    -1.36788275407234, -1.28168637109063), pred2 = c(-1.42361872090391, 
    -1.3982815502715, -1.1409241475472, -1.1331066959139, -1.12562914109629, 
    -1.11814749991547)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

我想在x轴上有月份,在y轴上有年份,并为pred1和pred2绘制折线图并进行图形比较。 感谢您在进行R

方面的帮助

1 个答案:

答案 0 :(得分:0)

这就是我对围绕y轴表示年份的问题的理解-我已将其放入垂直方面,每个方面中都有一个折线图,x上为月份,y上值为。如果这不是您要尝试的操作,请澄清您的原始问题。

ggplot(df1, aes(month)) +
  geom_line(aes(y = pred1), color = "blue") +
  geom_line(aes(y = pred2), color = "red") +
  facet_grid(year~.)

enter image description here

如果您想让图例区分这两个系列,则最简单的方法是将数据重整形为长格式,以便系列名称是可以映射为颜色(例如颜色)的变量。

library(dplyr)
df1 %>%
  tidyr::gather(series, value, pred1:pred2) %>%
  ggplot(aes(month, value, color = series)) +
  geom_line() +
  facet_grid(year~.)

enter image description here