C8H*_*4O2 9 if-statement r colors histogram ggplot2
我想做一个直方图,其中填充颜色根据bin的低端而变化.我不想手动填充.这个答案似乎很有希望,但我无法将其成功转换为直方图和双值(非渐变)颜色方案.我相信解决方案可能是一些ifelse
逻辑,geom_histogram(fill= )
但我不知道如何访问bin起始值.
例如,在下面的直方图中,我想将收入超过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")
Run Code Online (Sandbox Code Playgroud)
此外,我尝试使用第二个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
Run Code Online (Sandbox Code Playgroud)
cde*_*man 15
最简单的方法是添加具有条件的另一列并更新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")
Run Code Online (Sandbox Code Playgroud)
如果您对某些特定颜色设置了心脏,则可以使用该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")
Run Code Online (Sandbox Code Playgroud)