如何在ggplot直方图中定义填充颜色?

时间:2010-03-30 14:33:16

标签: r ggplot2

我有以下简单数据

data <- structure(list(status = c(9, 5, 9, 10, 11, 10, 8, 6, 6, 7, 10, 
10, 7, 11, 11, 7, NA, 9, 11, 9, 10, 8, 9, 10, 7, 11, 9, 10, 9, 
9, 8, 9, 11, 9, 11, 7, 8, 6, 11, 10, 9, 11, 11, 10, 11, 10, 9, 
11, 7, 8, 8, 9, 4, 11, 11, 8, 7, 7, 11, 11, 11, 6, 7, 11, 6, 
10, 10, 9, 10, 10, 8, 8, 10, 4, 8, 5, 8, 7), statusgruppe = c(0, 
0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, NA, 0, 1, 0, 1, 
0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 
1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 
1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0)), .Names = c("status", 
"statusgruppe"), class = "data.frame", row.names = c(NA, -78L
))
从那里我想做一个直方图:

ggplot(data, aes(status))+
geom_histogram(aes(y=..density..),
     binwidth=1, colour = "black",
     fill="white")+
theme_bw()+
scale_x_continuous("Staus", breaks=c(min(data$status,na.rm=T), median(data$status, na.rm=T), max(data$status, na.rm=T)),labels=c("Low", "Middle", "High"))+
scale_y_continuous("Percent", formatter="percent")

现在 - 我希望垃圾箱根据价值采取colou - 例如有价值的箱子> 9变成深灰色 - 其他一切都应该是浅灰色。

我尝试了fill=statusgruppescale_fill_grey(breaks=9)等等 - 但我无法让它发挥作用。有什么想法吗?

3 个答案:

答案 0 :(得分:14)

希望这可以让你开始:

ggplot(data, aes(status, fill = ..x..))+
  geom_histogram(binwidth = 1) + 
  scale_fill_gradient(low = "black", high = "white")

ggplot(data, aes(status, fill = ..x.. > 9))+
  geom_histogram(binwidth = 1) + 
  scale_fill_grey()

答案 1 :(得分:0)

如何在fill=..count..之后立即使用fill=I(..count..>9)y=..density..?你必须修改一下图例标题和标签,但它才能正确着色。

编辑:
我似乎误解了你的问题。如果要根据x坐标定义颜色,可以类似地使用..x..自动变量。

答案 2 :(得分:0)

scale_manual怎么样?这是Hadley网站的link。我已经使用此功能为箱线图设置了合适的填充颜色。不确定它是否适用于直方图,但是......

相关问题