Assign colours to values and plot horizontal bars in R

别等时光非礼了梦想. 提交于 2020-01-06 08:14:24

问题


with a data frame of 3 columns, i would like to assign the colour "red" to values below 19.293 and "blue" to values above 19.293.

dataframe123 <- data.frame(hmin1, hmin2, hmin3)

The following are the values in the data frame hmin1:

c(3.93999999999999, 6.13333333333333, 8.12727272727273, 9.94782608695652, 
11.6166666666667, 13.152, 14.5692307692308, 15.8814814814815, 
17.1, 18.2344827586207, 19.2933333333333, 20.2838709677419, 21.2125, 
22.0848484848485, 22.9058823529412, 23.68, 24.4111111111111, 
25.1027027027027, 25.7578947368421, 26.3794871794872, 26.97)

hmin2:

c(17.7688888888889, 17.9866666666667, 18.2044444444444, 18.4222222222222, 
18.64, 18.8577777777778, 19.0755555555556, 19.2933333333333, 
19.5111111111111, 19.7288888888889, 19.9466666666667, 20.1644444444444, 
20.3822222222222, 20.6, 20.8177777777778, NA, NA, NA, NA, NA, 
NA)

hmin3:

c(9.29333333333333, 10.2933333333333, 11.2933333333333, 12.2933333333333, 
13.2933333333333, 14.2933333333333, 15.2933333333333, 16.2933333333333, 
17.2933333333333, 18.2933333333333, 19.2933333333333, 20.2933333333333, 
21.2933333333333, 22.2933333333333, 23.2933333333333, 24.2933333333333, 
25.2933333333333, 26.2933333333333, 27.2933333333333, 28.2933333333333, 
29.2933333333333)

After assigning "red" and "blue", i intend to plot them as 3 bars horizontally, where the bars take on the range of values of hmin1, hmin2 and hmin3.

So far, i have been using barplot() and it outputs stacked values instead of the range, using the following code:

dataframe123 <- as.matrix(dataframe123)
barplot(dataframe123, horiz = TRUE)

How do i go about plotting the range of values for hmin1-3 and colour code them based on the first sentence in this question?

Any help would be appreciated. Thank you.


回答1:


You can get the ranges that you want using the range function.

FullRange = range(dataframe123, na.rm=TRUE)
FullRange
[1]  3.94000 29.29333
BoxRanges = lapply(dataframe123, range, na.rm=TRUE)
BoxRanges
$hmin1
[1]  3.94 26.97
$hmin2
[1] 17.76889 20.81778
$hmin3
[1]  9.293333 29.293333

Once you have that, you can get the barplots that you are looking for by making an empty plot and then plotting some rectangles.

plot(NULL, xlim=FullRange, ylim=c(0,3),  yaxt="n", xlab="Value", ylab="")
abline(v=19.293)
axis(2, at=(0:2)+0.4, labels=c("hmin1", "hmin2","hmin3"), 
    lty=0, las=2)

for(i in 1:3) {
    polygon(c(BoxRanges[[i]][1], BoxRanges[[i]][1], 19.293, 19.293), 
        c(i-1,i-0.2,i-0.2,i-1), col="red")
    polygon(c(19.293, 19.293, BoxRanges[[i]][2], BoxRanges[[i]][2]), 
        c(i-1,i-0.2,i-0.2,i-1), col="blue")
}



来源:https://stackoverflow.com/questions/54974629/assign-colours-to-values-and-plot-horizontal-bars-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!