Create a facet with 2 multiple-line charts

Hi so I have got my 2 separated line charts with 3 lines on each chart done. Now I want to put them on a facet with one on top another. How can I do this?

Here is my code:

ggplot(chinamor, aes(x=`Year`))+
  geom_line(aes(y=`China Life Expectancy`), color="red")+
  geom_line(aes(y=`Russia Life Expectancy`), color="blue")+
  geom_line(aes(y=`United Kingdom Life Expectancy`), color="yellow")

ggplot(chinamor, aes(x=`Year`))+
  geom_line(aes(y=`China Mortality`), color="red")+
  geom_line(aes(y=`Russia Mortality`), color="blue")+
  geom_line(aes(y=`United Kingdom Mortality`), color="yellow")

Thank you!

The easiest solution, I think, is to reshape your data to have the columns Year, Country, Variable, and Value. The Variable column would have the values Life Expectancy and Mortality. The ggplot code could then be

ggplot(chinamor_reshaped, aes(x = Year, y = Value, color = Country)) + geom_line() +
  facet_wrap(~ Variable, ncol = 1) +
  scale_color_manual(values = c(China = "red", Russia = "blue", United Kingdom = "yellow"))

I have not tested that code since I don't have your data. If you need more help, please post the output of

dput(chinamor)

or if the data set is very large,

dput(head(chinamor, 25))

where 25 is the number of rows of data. Change that to a value that makes sense for your data.

I used bingchat to generate example data.

library(tidyverse)

chinamor <- tibble(
  Year = c(2000, 2001, 2002),
  `China Life Expectancy` = c(71.7, 72.2, 72.7),
  `Russia Life Expectancy` = c(65.3, 65.4, 65.9),
  `United Kingdom Life Expectancy` = c(77.7, 78.1, 78.5),
  `China Mortality` = c(7.18, 7.08, 6.95),
  `Russia Mortality` = c(14.65, 14.58, 14.39),
  `United Kingdom Mortality` = c(10.28, 10.22, 10.16)
)

# reshaping :
(df_long <- chinamor |> pivot_longer(cols = -Year) |> mutate(
  stat_type = case_match(
    str_detect(name, fixed("Mort")),
    FALSE ~ "Expectancy",
    TRUE ~ "Mortality"
  ),
  name = str_replace_all(name, "Mortality|Life Expectancy", "") |> trimws()
) |> arrange(stat_type, Year, name))

pcolors <- c(
  "China" = "red",
  "Russia" = "blue",
  "United Kingdom" = "yellow"
)

ggplot(df_long) +
  aes(
    x = Year,
    y = value,
    color = name
  ) +
  geom_line() +
  facet_wrap(~stat_type,
    scales = "free",
    nrow = 2
  ) +
  scale_color_manual(values = pcolors) +
  scale_x_continuous(breaks = unique(df_long$Year))

another option is to continue with your independent charts, and stitch them together.
libraries patchwork and cowplot support that sort of thing.

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