CodexBloom - Programming Q&A Platform

Trouble with plotting multiple time series on the same graph using ggplot2 in R

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-28
ggplot2 data-visualization tidyverse R

I'm updating my dependencies and Hey everyone, I'm running into an issue that's driving me crazy. I'm trying to create a single plot that shows multiple time series from a data frame using the `ggplot2` package, but I'm running into issues with the formatting of my data. I've got a data frame that looks like this: ```r library(tidyverse) df <- data.frame( Date = as.Date('2021-01-01') + 0:9, Series_A = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Series_B = c(10, 9, 8, 7, 6, 5, 4, 3, 2, 1), Series_C = c(5, 6, 7, 8, 9, 10, 9, 8, 7, 6) ) ``` I've reshaped the data into a long format using `pivot_longer()`: ```r df_long <- df %>% pivot_longer(cols = -Date, names_to = "Series", values_to = "Value") ``` When I try to plot it, I use the following code: ```r ggplot(df_long, aes(x = Date, y = Value, color = Series)) + geom_line() + labs(title = "Multiple Time Series", x = "Date", y = "Value") ``` However, I am getting a plot where all the lines are overlapping and it's not clear which series is which. The legend is also not showing the correct colors. I suspect I might not be handling the factors correctly or there could be an scenario with how I've set up the aesthetics for `ggplot2`. I've gone through the documentation and tried different combinations, but I haven't been able to resolve it. Could someone guide to understand what I might be doing wrong? I'm using `ggplot2` version 3.3.5, and I have the latest version of `tidyverse` installed. I'm working on a CLI tool that needs to handle this. What am I doing wrong? This issue appeared after updating to R 3.9.