How to insert a legend in a GGPLOT with multiple time series

和自甴很熟 提交于 2021-02-05 09:29:47

问题


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..

I tried:

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...

Thanks!


回答1:


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.

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



来源:https://stackoverflow.com/questions/64523271/how-to-insert-a-legend-in-a-ggplot-with-multiple-time-series

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!