Trying to draw a multi-line graph with ggplot2

Hello, this is my first participation in the community. I'm very new to r and I'm trying to do something that I think should be simple but I haven't found the right key. I have this dataframe:

ggp <- data.frame(
  stringsAsFactors = FALSE,
             Month = c("01-2021", "02-2021", "03-2021", "04-2021"),
               Eur = c(4666395L, 6710095L, 8426865L, 7365811L),
              Tons = c(7677L, 11092L, 13930L, 11709L)
)

I am trying to plot a graph with multiple lines in ggplot2:

ggp1 <- ggplot(ggp, aes(Month)) +      
  geom_line(aes(y = Eur), colour = "red") +
  geom_line(aes(y = Tons), colour = "blue")

gives me this error:

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

(actually with any code I've tried I get the same result)

I hope I have put my question correctly. Any hints on how to do it correctly? Thanks in advance

Here are two ways to make the plot. The second method is the standard way to plot multiple series with ggplot, using the data in a "long" format where one column labels which group applies to the data and another column hods the value. This is much easier to use when there are several groups because you do not have to write an explicit geom_line for every one. I used a function from tidyr to reshape the data into the long format.

ggp <- data.frame(
  stringsAsFactors = FALSE,
  Month = c("01-2021", "02-2021", "03-2021", "04-2021"),
  Eur = c(4666395L, 6710095L, 8426865L, 7365811L),
  Tons = c(7677L, 11092L, 13930L, 11709L)
)

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5
ggplot(ggp, aes(Month)) +      
  geom_line(aes(y = Eur), colour = "red", group = "Eur") +
  geom_line(aes(y = Tons), colour = "blue", group = "Tons")


library(tidyr)
ggpLong <- ggp %>% pivot_longer(cols = Eur:Tons, names_to = "Category", values_to = "Value")
ggplot(ggpLong, aes(x = Month, y = Value, color = Category, group = Category)) + geom_line()

Created on 2021-08-16 by the reprex package (v0.3.0)

Great. Thanks a lot FJCC.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.