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

2023-12-13

给定一个数据框如下:

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

我想用 ggplot 画一个图:barchart for city, point for pct,但我想为负值和正值使用不同的颜色。

我怎样才能在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)

您可以使用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)

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐