直方图条件填充颜色

Histogram conditional fill color

我想制作一个直方图,其中填充颜色根据 bin 的低端而变化。我不希望 manual fill. This answer 看起来很有前途,但我无法将其成功转换为直方图和二值(非渐变)配色方案。我相信解决方案可能是 geom_histogram(fill= ) 中的一些 ifelse 逻辑,但我不知道如何访问 bin 起始值。

例如,在下面的直方图中,我想将超过 100,000 美元的收入箱涂成红色以显示高收入客户。

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

此外,我尝试了 workaround 和第二个 geom_histogram(),但没有成功。

ggplot(cust, aes(x=cust_rev)) + 
  geom_histogram(color="black",fill="light blue", binwidth=1/3) + 
  geom_histogram(data=subset(cust,cust_rev>100000),
                 color="black",fill="red", 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")
# Error in data.frame(x = c(45291.1377418786, 52770.7004919648, 15748.975193128,
#   : arguments imply differing number of rows: 10000, 3568

最简单的方法是添加另一列具有条件并更新 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")

如果您喜欢某些特定的颜色,可以使用 scale_fill_manual 功能。这是一个带有一些有趣的明亮颜色的示例。

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) +
    scale_fill_manual(values = c("green", "purple")) +
    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()