使用R中的abline函数使用不同颜色的直方图 [英] Histogram with different colours using the abline function in R

查看:493
本文介绍了使用R中的abline函数使用不同颜色的直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个具有不同颜色和图例的直方图.

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

假设以下数据:

df1<- rnorm(300,60,5)

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

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.

推荐答案

这是使用ggplot2dplyrtidyr的一种方法.

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

首先,您需要设置颜色.我用mutatecase_when来做到这一点.对于图本身,重要的是要记住,如果直方图图元未对齐,则可以在同一条上获得不同的颜色.为避免这种情况,可以使用binwidth=1.

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

评论中的其他请求

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

这篇关于使用R中的abline函数使用不同颜色的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆