Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set different colors in geom_point for negative and positive values in ggplot2

Tags:

r

ggplot2

Given a dataframe as follows:

df <- data.frame(city = c("bj", "sh", "gz", "sz"),
                 price = c(12, 7, 5, 6),
                 pct = c(-2.3, 5, -4, 4), stringsAsFactors=FALSE)

Out:

  city  price  pct
0   bj     12 -2.3
1   sh      7  5.0
2   gz      5 -4.0
3   sz      6  4.0

I want to draw a plot with ggplot: barchart for city, point for pct, but I want to have different colors for negative and positive values.

How can I do that in ggplot2?

Code:

ggplot(df, aes(fill = city, y = price, x = city)) + 
    geom_bar(position = "dodge", stat = "identity", alpha = 0.5, fill = "#FF6666") +
    geom_point(data = df,  aes(x = city, y = pct), size = 2)
like image 514
ah bon Avatar asked Oct 24 '25 13:10

ah bon


1 Answers

You can use pct>0 as color (0 or 1 depending on sign of pct) and transform city in a factor :

ggplot(df, aes(fill = city, y = price, x = city)) + 
    geom_bar(position = "dodge", stat = "identity", alpha = 0.5, fill = "#FF6666") +
    geom_point(data = df,  aes(x = factor(city), y = pct, color = pct>0), size = 2)

enter image description here

like image 134
Waldi Avatar answered Oct 26 '25 10:10

Waldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!