2010-03-30 63 views
8

我有以下简单的数据如何在ggplot直方图中定义填充颜色?

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=statusgruppe,scale_fill_grey(breaks=9)等 - 但我不能得到它的工作。有任何想法吗?

回答

11

这应该可以让你开始:

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

谢谢 - 我改变了这样的legendlabel(为后代) scale_fill_grey(“Name”,breaks = c(FALSE,TRUE),标签= c(“This”,“That”))。 另一个问题,但: - 是否有可能做一些像..x ..> 7,..x ..> 9(如果我想要三个类别,而不是只有两个?) – Andreas 2010-03-31 13:36:16

+1

在这种情况下,使用'cut' 。 – hadley 2010-03-31 14:31:42

+2

谢谢! - 如果有其他人感兴趣,这是我如何做到的:fill = cut(.. x ..,c(1,6,10))), binwidth = 1,color =“black”, )+ scale_fill_grey( “name”,breaks = c(“(1,6)”,“(6,10)”,NA),labels = c(“Low”,“Midle”,“High”))+ – Andreas 2010-03-31 15:37:44

0

如何在y=..density..之后使用fill=..count..fill=I(..count..>9)?你必须修改图例的标题和标签,但它有正确的着色。编辑:
看来我误解了你的问题了一下。如果要根据x坐标定义颜色,则可以使用类似的自动变量..x..

+0

谢谢你的好点子!然而 - 伯爵不是我想表现出来的。我希望bin-bar的颜色取决于该bin表示的值(而不是count)。即不是超过9计数的箱子,但是数值大于9. 我不认为我擅长解释这一点: -/ 也许这是我的轴标签混淆了我。我想要的是在标签“中间”的右侧给容器着色 – Andreas 2010-03-30 15:31:56

0

scale_manual怎么样?这里是Hadley网站的link。我已经使用这个函数为boxplot设置了合适的填充颜色。不知道这是否会与直方图工作,虽然...