问题描述
我正在尝试从plot切换到ggplot2并遇到一些实际的麻烦.下面,我为想要获得的情节附加了一些代码的非常简化的版本:
I am trying to switch from plot to ggplot2 and experience some real trouble. Below, I have attached a very simplified version of some code for the plot I would like to obtain:
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代码:
I then would like to plot both series, x and y, with the date on the x axis. I would like the first series displayed with red dotted lines and the second series with a black line, as well as obtaining a legend. This is my ggplot2 code I used so far:
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")
geom_line(data = datframe, aes(x=datframe$date, y=datframe$y, linetype="y"),color = "black")
好吧,问题是我只有一个图例条目,而且我不知道如何更改它.我真的很感谢一些提示,我已经花了很长时间在一个简单的图表上,无法弄清楚.我认为对于您的高级用户来说,这可能是显而易见的,对初学者的问题感到抱歉,但在此先感谢您的帮助.
Well, the problem is that I only have one legend entry and I do not know how to change it. I would really appreciate some hints, I already spent a long time on a simple graph and could not figure it out. I think for you advanced users it might be obvious, sorry for the beginner question but I thank you a lot in advance for any help.
推荐答案
我建议您先整理数据集(将其从宽变长),然后再使用 scale_linetype | color_manual
:
I would recommend tidying your data set first (changing it from wide to long) and then using 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
结合使用,但是感觉有点怪异":
Alternatively, you can use I()
in the aesthetic calls in conjunction with scale_color_manual
, but this feels a bit more "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"))
这篇关于ggplot2的两个时间序列的简单图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!