user15473160
user15473160

Reputation: 68

Plotting Legends in GGPLOT with Mutiple Time Series

I am relatively new to R, I am trying to work on multiple time series plots with ggplot but however as much as I have tired, there seems to be an issue with plotting legends. I have tried to use +theme(legends.) but this also is not giving any outputs. Given below is the code, would it be possible for anyone to have a look into this and let me know how to plot the legends in this situation. The datasets here contains gross revenue of these companies over the span of 2009-2020.

ggplot(dataset,aes(x=Year,y=Apple))+geom_line(color=5)+geom_line(aes(x=Year,y=Intel),colour=10)+geom_line(aes(x=Year,y=BOB),color=11)+geom_line(aes(x=Year,y=Airbus),color=12)+geom_line(aes(x=Year,y=SYNTEL),color=13)+geom_line(aes(x=Year,y=Google),color=14)+geom_line(aes(x=Year,y=Ebay),color=15)+ theme_light() +labs(x="Years",y="Spending",title = "Customer Spending on Companies per Year")

Upvotes: 1

Views: 77

Answers (1)

altfi_SU
altfi_SU

Reputation: 588

I guess your data is in a wide format given your original code. Best thing to do is to manipulate it to long format using pivot_longer() from tidyr so that you have three variables. Then it is easy to create a legend for your chosen variable. Do this with aes() in geom_line(). Remember that the variable that you want to show in different colours needs to be a factor. You can do this before the ggplot pipes or in it. I have manually adjusted the the title of the legend in labs(). There are various was to change the colours and you should be able to find some ways on the internet.

library(tidyr)
library(ggplot2)

Year <- 2009:2020
Apple <- cumsum(rnorm(12, 200, 22))
Intel <- cumsum(rnorm(12, 500, 12))
BOB <- cumsum(rnorm(12, 300, 8))
Airbus <- cumsum(rnorm(12, 500, 22))
Syntel <- cumsum(rnorm(12, 150, 15))
Google <- cumsum(rnorm(12, 500, 10))
Ebay <- cumsum(rnorm(12, 300, 1))

dataset <- data.frame(Year, Apple, Intel, BOB, Airbus, Syntel, Google, Ebay)
dataset <- dataset %>% 
  pivot_longer(cols = Apple:Ebay, names_to = "Company", values_to = "values") 

ggplot(dataset, aes(x = Year, y = values)) +
  geom_line(aes(colour = as.factor(Company))) +
  labs(x="Years",y="Spending", title = "Customer Spending on Companies per Year", colour = "Company")

Upvotes: 1

Related Questions