Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

r - ggplot: manual color assignment for single variable only

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...