R中的部分颜色直方图

dar*_*age 15 r colors histogram

在此输入图像描述

我有一个直方图,如图所示.我希望两个区域中的条纹分别用红色和绿色着色,即从0到左边第一个黑色边框的条形应为红色,第二个区域中的条形应为绿色.这可以在R中完成吗?用于获取直方图的代码是

hist(pr4$x[pr4$x[,1]>-2,1],breaks=100)
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 24

执行此操作的最佳方法是允许hist为您进行计算,然后使用hist(再次)进行实际绘图.这是一个例子:

set.seed(1)
x <- rnorm(1000)
h <- hist(rnorm(1000), breaks=50, plot=FALSE)
cuts <- cut(h$breaks, c(-Inf,-.5,1.75,Inf))
plot(h, col=cuts)
Run Code Online (Sandbox Code Playgroud)

最后一行中的.5和1.75是您想要具有不同颜色的阈值.

注意:我使用的是原始答案barplot,但该策略使得轴难以使用.

这是结果:

在此输入图像描述

  • 你可以在直方图对象上调用`plot`,而不是再次对数据调用`hist`. (2认同)

Spa*_*man 16

这是我在评论中提到的方法:

制作一些测试数据(你应该在你的问题中做到这一点!)

test = runif(10000,-2,0)
Run Code Online (Sandbox Code Playgroud)

得到R来计算直方图但不绘制它:

h = hist(test, breaks=100,plot=FALSE)
Run Code Online (Sandbox Code Playgroud)

您的直方图分为三个部分:

ccat = cut(h$breaks, c(-Inf, -0.6, -0.4, Inf))
Run Code Online (Sandbox Code Playgroud)

使用此调色板绘制,将因子隐式转换为数字索引调色板:

plot(h, col=c("white","green","red")[ccat])
Run Code Online (Sandbox Code Playgroud)

彩色条

ggplot2 解决方案也可用.