Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...