如何对直方图进行部分着色?

问题描述 投票:0回答:1

我一直在尝试在以下数据帧(df)中对高于定义阈值的特定仓进行着色

df <- read.table("https://pastebin.com/raw/3En2GWG6", header=T)

我一直按照这个例子(在R中改变特定直方图的颜色。), 但我似乎不能让这个来适应他们的建议,以我的数据因此,我想问你在stackoverflow的

我希望所有数值在0.100以上的bin都是 "红色",其余的要么是没有颜色,要么就是黑色(我定义了黑色,但我更喜欢没有颜色)。

这是我试过的。

col<-(df$consumption>=0.100)
table(col) # I can see 40 points above 100, the rest below

col[which(col=="TRUE")] <- "firebrick1"
col[which(col=="FALSE")] <- "black"

hist(df$consumption, breaks = 1000, xlim = c(0,0.2), col=col,xlab= "Consumption [MG]")

但是.., 一体 图是红色的,这没有意义...?

换句话说,我想 任何 向右下方的线是红色的。

hist(df$consumption, breaks = 1000, xlim = c(0,0.2),xlab= "Consumption [MG]")
abline(v=c(.100), col=c("red"),lty=c(1), lwd=c(5))
r histogram
1个回答
1
投票

只需在两幅直方图的顶部使用 add=TRUE 并分设第二种。

hist(df$consumption, breaks=1000, xlim=c(0,.2),xlab= "Consumption [MG]")
hist(df$consumption[df$consumption > .100], breaks=1000, xlim=c(0,.2), col=2, add=TRUE)

abline(v=.100, col=2, lty=3)

enter image description here


1
投票

这里是沿着你所做的思路。你不想计算截止点以上的点数,而是计算截止点以上的直方块数。

# store the histogram as an object
h <- hist(df$consumption, breaks = 1000)

# extract out the breaks, and assign a color vector accordingly
cols <- ifelse(h$breaks > 0.1, "firebrick1", "black")

# use the color vector
plot(h, col = cols, xlim=c(0,.2),xlab= "Consumption [MG]")
abline(v=c(.100), col=c("red"),lty=c(1), lwd=c(5))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.