简体   繁体   English

如何用y轴值对geom_bar进行着色?

[英]How to color geom_bar by y-axis values?

I'm making a standard bar plot with ggplot2 geom_bar. 我正在使用ggplot2 geom_bar制作标准条形图。 I'm trying to fill the bars with the highest values with a different color than the bars with the lowest values. 我试图用最高值填充条形,使用与具有最低值的条形图不同的颜色。

For example, 例如,

ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar()

How can you color bars above 20 in red (eg, E), bars from 10 to 20 in blue (B and D), and bars below 10 in orange (A and C). 如何在红色(例如,E)中将20以上的条纹,以蓝色(B和D)从10到20的条形,以及在橙色(A和C)中的10以下的条形。

Thanks for any insights! 感谢您的任何见解!

在此输入图像描述

I'm using geom_col and my actual code looks like this 我正在使用geom_col,我的实际代码看起来像这样

ggplot(data, aes(x=State, y=Value)) +
 geom_col()

You might use cut 你可能会使用cut

ggplot(mtcars, aes(x = as.factor(cyl))) +
  geom_bar(aes(fill = cut(stat(count), breaks = c(0, 8, 12, Inf)))) +
  labs(fill = "Breaks")

在此输入图像描述

You obviously need to adjust the breaks according to your needs / data. 你显然需要根据你的需要/数据调整休息时间。


edit 编辑

If we use geom_col instead of geom_bar we need to change fill = stat(count) to fill = value_column (whatever the value_column is but it should be the same as the one we mapped to y ). 如果我们使用geom_col而不是geom_bar我们需要将fill = stat(count)更改为fill = value_column (无论value_column是什么,但它应该与我们映射到y那个相同)。

Example: 例:

df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
  geom_col(aes(fill = cut(outcome, breaks = c(0, 2, 3, Inf)))) +
  labs(fill = "Breaks")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM