我的示例数据框架如下:
a <- structure(list(Middlepoint = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1,
12, 13, 14, 15, 16, 17, 18, 19, 1, 1, 5, 5, 4, 4, 3, 7, 18, 8,
8, 8, 8, 8, 8.5, 8.5)), .Names = "Middlepoint", class = "data.frame", row.names = c(NA,
-34L))我想创建一个binwidth = 1直方图,其特征如下:
library(ggplot2)
library(scales)
ggplot(a, aes(x = Middlepoint)) +
geom_histogram(aes(y = ..density.., fill=..density..), binwidth = 1) +
scale_x_continuous(breaks=0:19) +
scale_fill_continuous(low = "red", high = "green")现在,我无法搞清楚的是,如何将密度最高的垃圾桶(这里,宾8-9)涂成绿色,以及其他所有的垃圾桶涂上红色(没有渐变,只有直颜色)。
正如您可以从上面的代码中看到的那样,我能得到的最接近的结果是使用scale_fill_continuous()组件,它非常接近,但不是我想要看到的。我尝试过像ggplot change fill colour without losing colour gradient和R - ggplot2 histogram conditional fill color这样的线程。有什么想法,一般如何自定义填充直方图的垃圾箱?
发布于 2016-01-26 09:21:01
您需要将fill参数设置为一个factor,它需要两个级别:一个用于所有密度值,一个用于低于max的密度值,另一个用于最大密度:
ggplot(a, aes(x = Middlepoint)) +
geom_histogram(aes(y = ..density..,
fill = cut(..density.., c(0, sort(..density.., TRUE)[1:2]))),
binwidth = 1) +
scale_fill_manual("", values = c("red", "green")) +
theme_minimal()

https://stackoverflow.com/questions/35009971
复制相似问题