Home > OS >  geom_line use several lines on one plot
geom_line use several lines on one plot

Time:06-22

I am currently trying to do a line plot, representing the evolution over 3 years of the number of doctors in various type of operations (one line for each), and my dataframe looks like follows :

type of operation     number of doctors        year

ambulatoire             12                     2019
externe                 150                    2019
ambulatoire             19                     2020
externe                 3                      2020

I have tried the following code but it doesn't seem to work... could anyone help ?

ggplot(df)  
  geom_line(aes(x = df$year, y = df$"number of doctors", color = df$"type of operation"))

CodePudding user response:

Try this

   ggplot(df)  
      geom_line(aes(x = year,
                    y = `number of doctors`, 
                    color = `type of operation`))

CodePudding user response:

Try this

library(ggplot2)

df <-
  data.frame(
    type_of_operation = c("ambulatoire", "externe"),
    number_of_doctors = c(12, 150, 19, 3),
    year = c(2019, 2019, 2020, 2020)
  )

ggplot(df, aes(x = year, y = number_of_doctors, color=type_of_operation))  
  geom_line()

PS : if you want to keep space in your variables name, use this quote : ` instead of "

  • Related