R 直方图条件填充颜色

R 直方图条件填充颜色,r,if-statement,colors,ggplot2,histogram,R,If Statement,Colors,Ggplot2,Histogram,我想做一个直方图,其中填充颜色的变化取决于垃圾箱的低端。我不想吃饱。这似乎很有希望,但我无法成功地将其转换为直方图和二值(不是渐变)颜色方案。我相信解决方案可能是ifelsegeom_直方图(fill=)中的一些逻辑,但我不知道如何访问bin起始值 例如,在下面的柱状图中,我想将超过100000美元的收入箱涂成红色,以显示高收入客户 library(ggplot2) library(scales) n <- 10000 cust <- data.frame(cust_id=1:n,

我想做一个直方图,其中填充颜色的变化取决于垃圾箱的低端。我不想吃饱。这似乎很有希望,但我无法成功地将其转换为直方图和二值(不是渐变)颜色方案。我相信解决方案可能是
ifelse
geom_直方图(fill=)中的一些逻辑,但我不知道如何访问bin起始值

例如,在下面的柱状图中,我想将超过100000美元的收入箱涂成红色,以显示高收入客户

library(ggplot2)
library(scales)

n <- 10000
cust <- data.frame(cust_id=1:n,cust_rev <- rexp(n,.00001))

# I want to use a log scale for my tick marks and bin breaks
powers <- function(base,exp) sapply(1:exp, function(exp) base^exp )

ggplot(cust, aes(cust_rev)) + 
  geom_histogram(color="black",fill="light blue", binwidth=1/3) + 
  scale_x_log10(labels=comma, breaks=powers(10,8)) +
  scale_y_continuous(labels=comma) +
  xlab("Customer Revenue") + ylab("Number of Customers") +
  ggtitle("Distribution of Customer Value")

最简单的方法是添加另一列条件并更新
aes
以包含填充组

cust$high_rev <- as.factor((cust[,2]>100000)*1)

ggplot(cust, aes(cust_rev, fill=high_rev)) + 
    geom_histogram(color="black", binwidth=1/3) + 
    scale_x_log10(labels=comma, breaks=powers(10,8)) +
    scale_y_continuous(labels=comma) +
    xlab("Customer Revenue") + ylab("Number of Customers") +
    ggtitle("Distribution of Customer Value")
这个怎么样

ggplot(cust, aes(cust_rev)) + 
  geom_histogram(aes(fill=cust_rev > 100000),binwidth=1/3) + 
  scale_x_log10()
或同等地

ggplot(cust, aes(x=cust_rev,fill=cust_rev > 100000)) + 
  geom_histogram(binwidth=1/3) + 
  scale_x_log10()

接受使用
比例填充手册()
。然而,正如下面ziggystar(+1)所建议的,我跳过了向df添加列,并直接将条件传递给aes(fill=)。此外,我还向绘图中添加了
指南(fill=FALSE)
,以抑制图例。虽然在本例中,我的选择比公认的答案更简洁、更好,但这不允许按多个条件填充。。。公认的答案将允许。。。或者我忽略了什么?如果你可以构造一些返回不同值的表达式(例如使用switch或cut),你就可以这样做。但这样会变得有点混乱,我建议增加一个专栏。
ggplot(cust, aes(cust_rev)) + 
  geom_histogram(aes(fill=cust_rev > 100000),binwidth=1/3) + 
  scale_x_log10()
ggplot(cust, aes(x=cust_rev,fill=cust_rev > 100000)) + 
  geom_histogram(binwidth=1/3) + 
  scale_x_log10()