Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: manual color assignment for single variable only

Tags:

r

ggplot2

I have this plot:

ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() + 
  xlab('Year') + ylab('GDP per capita')
  labs(title = "Annual GDP Growth rate (%)") +
  theme_bw()

enter image description here

Now I want to change color and line thickness (black, and a about 30% thicker than others) for one variable only (for one country only).

I have found how to manually assign colors for all variables, but not how to do it for only one. Also, graph can have different number of variables (countries), depending on input data.

like image 425
user1754606 Avatar asked Nov 10 '13 22:11

user1754606


1 Answers

A bit difficult without some reproducible data, but you should be able to achieve this by adding a geom_line() that only uses the data for that specific country:

ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() + 
  xlab('Year') + ylab('GDP per capita') +
labs(title = "Annual GDP Growth rate (%)") +
  theme_bw() +
  geom_line(data=subset(data3, country == "China"), colour="black", size=1.5)

Keeping the legend in line with the colour and size is a bit trickier- you can do it by manually hacking at the legend with override.aes, but it's not necessarily the most elegant solution:

# Needed to access hue_pal(), which is where ggplot's
# default colours come from
library(scales)

ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() + 
  xlab('Year') + ylab('GDP per capita') +
  labs(title = "Annual GDP Growth rate (%)") +
  theme_bw() +
  geom_line(data=subset(data3, country == "World"), colour="black", size=1.5) +
  guides(colour=guide_legend(override.aes=list(
    colour=c(hue_pal()(11)[1:10], "black"), size=c(rep(1, 10), 1.5))))
like image 127
Marius Avatar answered Sep 29 '22 23:09

Marius