error plotting multiple lines with ggplot and adding legend

Hi,
I got this error "Error in (function (s, units = "user", cex = NULL, font = NULL, vfont = NULL, :
plot.new has not been called yet"
code:

tlibrary(ggplot2)
#grafiek leeftijd tot omtrek
data<-Orange_15column

ggplot(data, aes(x=age), color=group) +
  #lines tree
  geom_line( aes(y=circum1), size=1,colour="blue") +
  geom_line( aes(y=circum2), size=1,colour="green") +
  geom_line( aes(y=circum3), size=1,colour="yellow") +
  geom_line( aes(y=circum4), size=1,colour="orange") +
  geom_line( aes(y=circum5), size=1,colour="white") +
  #lines climate
  geom_line( aes(y=appreciationavg*10, size=1), colour="red") +
  geom_line( aes(y=tempmax, size=1), colour="red") +
  geom_line( aes(y=tempmin, size=1), colour="red")+
  geom_line( aes(y=percipation_max, size=1),colour="red")

legend("right",
         pch = 16,
         cex = 0.8,
         horiz = FALSE,
         legend = c("Tree1","Tree2","Tree3","Tree4","Tree5"),
         col =  c("blue","green","yellow","orange","white"))

Thanks in advance for help,
Nobel

the bulk of your code is ggplot2 ; but then the final expression legend(... is a base plotting functionality; as you have not established any base plotting you are seeing an error.

in ggplot2, its most common to get legends 'for free' by establishing aes(thetic) relationships between your data and the ggplot2 system; you would refine them with scale_* functions and maybe theme-ing.

In ggplot2, we generally want our data to be in tidy-format so as to fully leverage the benefits; i.e. we establish relations with all the multiple lines to colour with only a single line of code ....

You would need to pivot_longer your data.

1 Like

Could you post the output of dput(Orange_15column)? That would help folks here figure out to best advise you.

You might find it easier to do this:

data <- Orange_15column |>
  tidyr::pivot_longer(cols = tidyr::starts_with("circum"), names_to = "circum", values_to = "value")

ggplot(data, aes(x=age)) +
  geom_line( aes(y=value, group = circum, colour=circum), size=1) +
  scale_colour_manual(values = c("blue", "green", "yellow", "orange", "white"))

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.