0
votes

I am trying to plot two lines with their respective legend on ggplot2 but have been unsuccessful so far. I've tried distinguishing them by line type on the geom_line field but the graph fails to plot. What could be the cause?

Example data:
x <- 
year    counts  amounts
2000    0   2
2001    1   2
2002    1   0
2003    0   1
2004    3   7
2005    1   11
2006    2   10
2007    2   12
2008    3   13
2009    3   15
2010    3   17

ggplot(x, aes(x = year)) +
  geom_line(aes(y = counts)) +
  geom_line(aes(y = amounts)) +
  theme_bw() 

Thanks for the help!

1
If you want to provide the sample data, please do so using dput() (see stackoverflow.com/questions/5963269/…). Also where exactly is your problem? You did not show any error messages...knytt

1 Answers

0
votes

Get the data in long format before plotting :

library(ggplot2)
library(dplyr)

df %>%
  tidyr::pivot_longer(cols = -year) %>%
  mutate(year  = factor(year)) %>%
  ggplot() + aes(year, value, group = name, color = name) + 
  geom_line() + theme_bw() 

enter image description here

data

df <- structure(list(year = 2000:2010, counts = c(0L, 1L, 1L, 0L, 3L, 
1L, 2L, 2L, 3L, 3L, 3L), amounts = c(2L, 2L, 0L, 1L, 7L, 11L, 
10L, 12L, 13L, 15L, 17L)), class = "data.frame", row.names = c(NA, -11L))