在geom_point中为ggplot2中的负值和正值设置不同的颜色

ahb*_*bon 4 r ggplot2

给定一个数据框如下:

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

出去:

  city  price  pct
0   bj     12 -2.3
1   sh      7  5.0
2   gz      5 -4.0
3   sz      6  4.0
Run Code Online (Sandbox Code Playgroud)

我想用 ggplot: barchartfor city, pointfor绘制一个图pct,但我想为负值和正值使用不同的颜色。

我怎样才能在ggplot2中做到这一点?

代码:

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)
Run Code Online (Sandbox Code Playgroud)

Wal*_*ldi 8

您可以使用pct>0颜色(0或1取决于 的符号pct)并city在因子 中进行变换:

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述