【问题标题】:Simple plot of two time series with ggplot2 [duplicate]用ggplot2绘制两个时间序列的简单图[重复]
【发布时间】:2018-04-02 20:03:48
【问题描述】:

我正在尝试从 plot 切换到 ggplot2 并遇到一些真正的麻烦。下面,我附上了我想获得的情节的一些代码的非常简化的版本:

x <- seq(1, 20, by=1)
y <- seq(1,40, by=2)


date <- seq(as.Date("2000/1/1"), as.Date("2001/8/1"), by = "month")
# I create a data frame with the date and TWO time series
datframe <- data.frame(date,x,y)

然后我想用 x 轴上的日期绘制两个系列 x 和 y。我想用红色虚线显示第一个系列,用黑线显示第二个系列,并获得一个图例。这是我目前使用的 ggplot2 代码:

ggplot() + geom_line(data = datframe, aes(x=date, y=datframe$x,group="x"), linetype="dotted", color="red") + 

geom_line(data = datframe, aes(x=datframe$date, y=datframe$y, linetype="y"),color = "black")

嗯,问题是我只有一个图例条目,我不知道如何更改它。我真的很感激一些提示,我已经花了很长时间在一个简单的图表上,但无法弄清楚。我认为对于您的高级用户来说,这可能是显而易见的,对于初学者的问题,我很抱歉,但我提前非常感谢您的帮助。

【问题讨论】:

    标签: r ggplot2 time-series


    【解决方案1】:

    我建议先整理您的数据集(将其从宽更改为长),然后使用scale_linetype|color_manual

    library(tidyverse)
    datframe.tidy <- gather(datframe, metric, value, -date)
    
    my_legend_title <- c("Legend Title")
    
    ggplot(datframe.tidy, aes(x = date, y = value, color = metric)) +
      geom_line(aes(linetype = metric)) +
      scale_linetype_manual(my_legend_title, values = c("dotted", "solid")) +
      scale_color_manual(my_legend_title, values = c("red", "black")) +
      labs(title = "My Plot Title",
           subtitle = "Subtitle",
           x = "x-axis title",
           y = "y-axis title"
    

    或者,您可以在审美调用中将I()scale_color_manual 结合使用,但这感觉有点“hacky”:

    ggplot(datframe, aes(x = date)) +
      geom_line(aes(y = x, color = I("red")), linetype = "dotted") +
      geom_line(aes(y = y, color = I("black")), linetype = "solid") +
      labs(color = "My Legend Title") +
      scale_color_manual(values = c("black", "red"))
    

    【讨论】:

    • 感谢一千次@JasonAizkalns,我现在明白你的结构了。这对我有很大帮助!
    【解决方案2】:

    ggplot 最适合“整洁”的数据框

    # make a tidy frame (date, variable, value)
    library(reshape2)
    datframe_tidy <- melt(datframe, id.vars = "date")
    
    # plot
    ggplot(datframe_tidy, aes(x = date, y = value, 
                              color = variable, linetype = variable)) +
      geom_line() +
      theme(legend.position = "bottom")
    

    【讨论】:

    • 非常感谢您的贡献,这也是一个非常简洁的解决方案!
    猜你喜欢
    • 2018-07-05
    • 2023-03-18
    • 2021-05-12
    • 2013-02-28
    • 2017-03-04
    • 2021-03-17
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    相关资源
    最近更新 更多