【问题标题】:Set different colors in geom_point for negative and positive values in ggplot2在geom_point中为ggplot2中的负值和正值设置不同的颜色
【发布时间】:2020-06-23 04:42:23
【问题描述】:

给定一个数据框如下:

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

输出:

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

我想用 ggplot 画一个图:barchart 代表citypoint 代表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)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用 pct&gt;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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2019-12-28
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      相关资源
      最近更新 更多