I have this dataframe: df_long:
year variable value
1970 Argentina 20
1980 Argentina 30
1990 Argentina 80
1970 Belgium 10
1980 Belgium 22
1990 Belgium 80
1970 U.S. 12
1980 U.S. 36
1990 U.S. 80
1970 Australia 11
1980 Australia 12
1990 Australia 90
I did this:
p <- ggplot(df_long, aes(year, value)) +
geom_line(aes(colour = variable, group = variable))
show(p)
And I can see 4 lines on the same plot, one for each country. But I don't know how to select these lines separately to manipulate them. For example, to give a red colour to the Argentina line, etc. Also, I would like to add a facet_grid() with 2 columns so I can see on the left plot lines from Argentina + Australia and on the right plot the lines from Belgium + U.S.
How can I divide the groupings so that I can do this?
Try this:
Add new column to your tibble
:
df <- df %>% mutate(group = case_when(
variable %in% c("Australia", "Argentina") ~ "group 1",
variable %in% c("Belgium", "U.S.") ~ "group 2"
))
Plot new df
:
ggplot(df, aes(year, value)) +
geom_line(aes(colour = variable, group = variable)) +
scale_color_manual(values=c("red", "blue", "green", "orange")) +
facet_wrap(~group)
With scale_color_manual()
you can control the colors individually for each line