我希望制作一个直方图,其中填充颜色取决于区间的低端。我不想要manual填充。这个answer看起来很有希望,但我无法成功将其转换为直方图和两个值(不是渐变)的颜色方案。我认为解决方案可能是在
例如,在下面的直方图中,我想用红色着色营收区间超过10万美元,以显示高收入客户。
geom_histogram(fill= )
中使用一些ifelse
逻辑,但我不知道如何访问区间起始值。例如,在下面的直方图中,我想用红色着色营收区间超过10万美元,以显示高收入客户。
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")
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
scale_fill_manual()
。但是,正如 ziggystar (+1) 在下面建议的那样,我跳过了向 df 添加列,并直接将条件传递给 aes(fill=))。此外,我在图中添加了guides(fill=FALSE)
来抑制图例。 - C8H10N4O2