如何在具有多个时间序列的GGPLOT中插入图例 [英] How to insert a legend in a GGPLOT with multiple time series

查看:40
本文介绍了如何在具有多个时间序列的GGPLOT中插入图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 GGPLOT 在单个图表上绘制多个时间序列.数据集是数据框架,第一列的日期为日期格式的日期为 Time ,其他列的时间序列的名称为 V1,V2 ...等.

I'm trying to plot multiple times series on a single graph with GGPLOT. The data set is a Data Frame with the dates in date format on the first column, named Time , and the times series on the other columns, named V1, V2...etc..

我尝试过:

gg1=ggplot() + 
  geom_line(data=PCA2, aes(x=Time, y=V2, group=1), lwd=1.1, color="red") +
  geom_line(data=PCA2, aes(x=Time, y=V3, group=1), lwd=1.1, color="blue")+
  scale_color_discrete(name = "PCA series", labels = c("V2", "V3"))
print(gg1)

但是我只是得到这个(没有图例):

but I just get this (without the legend):

任何人都可以帮忙吗?它应该可以正常工作,并且不会返回任何错误消息...

Can anyone help? it should work and it does not give back any error message...

谢谢!

推荐答案

在V2和V3变量中的值合并为一个新变量的意义上,您必须重塑数据以使其长",另一个变量指示数据的特定行是否引用了V2和V3.这是通过 tidyr 包中的 pivot_longer()实现的.

You have to reshape your data such that it is "long", in the sense that the values in the V2 and V3 variables are combined into a new variable, and another variable indicates whether a particular row of the data is referring to V2 and V3. This is achieved using pivot_longer() from the tidyr package.

以下是使用mtcars变量 drat wt 的示例,其作用与V2和V3对数据集的作用相同:

Here is an example using mtcars's variables drat and wt acting the same way V2 and V3 would act on your data set:

library(tidyverse)

dat <- mtcars %>% 
  select(drat, wt) %>% 
  mutate(x_axis = row_number()) %>% 
  pivot_longer(c(drat, wt), names_to = "variable", values_to = "values")

dat
#> # A tibble: 64 x 3
#>    x_axis variable values
#>     <int> <chr>     <dbl>
#>  1      1 drat       3.9 
#>  2      1 wt         2.62
#>  3      2 drat       3.9 
#>  4      2 wt         2.88
#>  5      3 drat       3.85
#>  6      3 wt         2.32
#>  7      4 drat       3.08
#>  8      4 wt         3.22
#>  9      5 drat       3.15
#> 10      5 wt         3.44
#> # ... with 54 more rows

ggplot(dat, aes(x = x_axis, y = values, colour = variable)) + 
  geom_line()

这篇关于如何在具有多个时间序列的GGPLOT中插入图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆