使用R中的abline函数绘制不同颜色的直方图

时间:2020-05-13 20:11:24

标签: r ggplot2 histogram

我想绘制带有不同颜色和图例的直方图。

假设以下数据:

df1<- rnorm(300,60,5)

我已使用以下代码使用abline函数获取直方图和线条:

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")

现在我想得到以下情节。我想删除这些行,但无法执行。因此,我不需要排队。 enter image description here

1 个答案:

答案 0 :(得分:1)

这是使用ggplot2dplyrtidyr的一种方法。

首先,您需要设置颜色。我使用mutatecase_when来做到这一点。对于图本身,重要的是要记住,如果直方图箱未对齐,则在同一条上可以得到不同的颜色。为避免这种情况,您可以使用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")

enter image description here

评论中的其他请求

使用case_when四种颜色:

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")

enter image description here

相关问题