Error when plotting line chart with ggplot

Hi there!
I'm trying to use multiple variables to plot a line chart to show a trend but for some reason that I cannot identify, the line charts are weird straight lines.

Here is a sample dataset:

df <- data.frame(stringsAsFactors=FALSE,
                 parent_location = c("Africa", "Europe", "Asia", "Latin America", "Middle East", "North America"),
                 location = c("Kenya", "Norway", "Thailand", "Brazil", "Turkey", "Canada"),
                 period = c(2016, 2016, 2016, 2016, 2016, 2016),
                 mortality_rate = c(101.4, 89.6, 88.3, 67.5, 77.4, 89.7))

Note: in my original dataset, the period ranges from the year 2000 to 2015 for each country so my sample data may be limiting but hope it gives you an idea of what I'm trying to achieve.


df |> 
  select(parent_location, mortality_rate, period) |> 
  group_by(parent_location, period) |> 
  summarise (mort_rate = mean(mortality_rate)) |> 
  ggplot(mapping = aes(
    x = period, 
    y = parent_location, 
    colour = parent_location)) + 

And here is the "silly" :upside_down_face: chart my code is dishing out

thanks for your help.

If you want the variables to be separated then you should use facets. Something like this should get you started:

df %>%  
  group_by(parent_location, period) %>% 
  summarise(mort_rate = mean(mortality_rate)) %>%  
  ungroup() %>% 
  ggplot(mapping = aes(
    x = period, 
    y = mort_rate, 
    colour = parent_location)) + 
  geom_line() + 
  facet_grid(rows = vars(parent_location))

thank you @martin.R , it works.
I found my error was using the parent_location on the y-axis instead of the mortality_rate. thanks again.

This topic was automatically closed 42 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.