本文介绍了为ggplot2中的负值和正值在geom_point中设置不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出如下数据框:

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 用于 city point 用于 pct ,但是我想要 pct 的负值和正值具有不同的颜色.

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

如何在ggplot2中做到这一点?谢谢.

How can I do that in ggplot2? Thanks.

代码:

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 转换为一个因子:

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))

这篇关于为ggplot2中的负值和正值在geom_point中设置不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 15:31