Histogram with different colours using the abline function in R

狂风中的少年 提交于 2020-05-28 08:38:09

问题


I would like to plot a histogram with different colours and legend.

Assuming the following data:

df1<- rnorm(300,60,5)

I have used the following codes to get the histogram plot and the lines using the abline function:

df1<-data.frame(df1)
attach(df1)
hist(M,at=seq(0,100, 2))
abline(v=80, col="blue")
abline(v=77, col="red")
abline(v=71, col="red")
abline(v=68, col="blue")
abline(v=63, col="blue")
abline(v=58, col="blue")
abline(v=54, col="blue")
abline(v=51, col="blue")
abline(v=457, col="blue")

Now I want to get the following plot. I wanted to remove the lines, but I was unable to do it. So I do not need to have the lines.


回答1:


Here's one way of doing that with ggplot2, dplyr and tidyr.

First you need to set the colors. I do that with mutate and case_when. For the plot itself, it's important to remember that if histogram bins are not aligned, you can get different colors on the same bar. To avoid this, you can use binwidth=1.

library(ggplot2)
library(dplyr)
library(tidyr)

df1 <- data.frame(data1=rnorm(300,60,5))
df1 <- df1 %>%
  mutate(color_name=case_when(data1<60              ~ "red",
                              data1>=60 & data1 <63 ~ "blue",
                              TRUE                  ~ "cyan")) 

ggplot(df1,aes(x=data1, fill=color_name)) +
  geom_histogram(binwidth = 1, boundary = 0, position="dodge") +
  scale_fill_identity(guide = "legend")

Additional request in comment

Using case_when with four colors:

df1 <- data.frame(data1=rnorm(300,60,5))
df1 <- df1 %>%
  mutate(color_name=case_when(data1<60              ~ "red",
                              data1>=60 & data1 <63 ~ "blue",
                              data1>=63 & data1 <65 ~ "orange",
                              TRUE                  ~ "cyan")) 
ggplot(df1,aes(x=data1, fill=color_name)) +
  geom_histogram(binwidth = 1, boundary = 0, position="dodge") +
  scale_fill_identity(guide = "legend")



来源:https://stackoverflow.com/questions/61783942/histogram-with-different-colours-using-the-abline-function-in-r

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