我的示例数据框如下:
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这样的线程 . 任何想法如何一般自定义填充直方图的箱子?
1 回答
您需要将
fill
参数设置为factor
,它需要2个级别:一个用于所有密度值低于max
,一个用于最大密度: