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
390 views
in Technique[技术] by (71.8m points)

r - change color of only one bar in ggplot

I want to color only one bar in ggplot. This is my data frame:

area <- c("Pó?noc", "Po?udnie", "Wschód", "Zachód")
sale <- c(16.5, 13.5, 14, 13)
df.sale <- data.frame(area, sale)
colnames(df.sale) <- c("Obszar sprzeda?y", "Liczba sprzedanych produktów (w tys.)")

And code for plotting:

plot.sale.bad <- ggplot(data=df.sale, aes(x=area, y=sale, fill=area)) +
  geom_bar(stat="identity") +
  scale_fill_manual(values=c("black", "red", "black", "black")) +
  xlab(colnames(df.sale)[1]) +
  ylab(colnames(df.sale)[2]) +
  ggtitle("Porównanie sprzeda?y") 

I would like to have only one bar colored and 3 others to have default color (darkgrey, not black, it looks bad for me). How can I change color of only on bar or how to get name of the default color of bars to put them instead of black?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you like having everything in the ggplot call, you can use an ifelse statement within factor() for the fill as shown below.

This also separates the legend into two categories (i.e. highlighted and not highlighted) so that you aren't repeating the values shown on the x axis. This also provides another illustrative dimension to the plot in the legend.

plot.sale.bad2 <- ggplot(data=df.sale,
                         aes(x=area,
                             y=sale,
                             fill=factor(ifelse(area=="Po?udnie","Highlighted","Normal")))) +
  geom_bar(stat="identity") +
  scale_fill_manual(name = "area", values=c("red","grey50")) +
  xlab(colnames(df.sale)[1]) +
  ylab(colnames(df.sale)[2]) +
  ggtitle("Porównanie sprzeda?y") 

plot.sale.bad2

Plot with legend

If the legend isn't needed you can add show.legend = FALSE to the geom_bar() call to produce the following:

Plot without legend


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

...