首页 文章

两个时间序列的简单绘图与ggplot2 [重复]

提问于
浏览
0

这个问题在这里已有答案:

我试图从情节切换到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和y两个系列,日期在x轴上 . 我想第一个系列用红色虚线显示,第二个系列用黑色线显示,以及获得一个图例 . 这是我到目前为止使用的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”)

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

2 回答

  • 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"
    

    Plot

    或者,您可以在审美调用中使用 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"))
    
  • 1

    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")
    

    enter image description here

相关问题