如何从R中的数据子集创建两个并排图? [重复]

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

这个问题在这里已有答案:

我有一个大的数据框架,基本上按年份划分(即有2004年和2005年的数据),我希望用2004年和2005年的数据创建两个并排的直方图。

我已经用这两年的数据创建了一个直方图,但是我很难根据年份将其分开。

library(ggplot2)
NextRatings <- read.csv("DataSet.csv", header = TRUE)

line <- ggplot(NextRatings, aes(x=rating.avg)) + 
           geom_histogram(aes (y = ..density..), binwidth = .5, colour = "black", fill = "white") + 
           geom_density(alpha = .2, colour = "blue")

这是两年生成直方图的代码,但我不知道如何根据年份将它们分成两个直方图。

r ggplot2 histogram
1个回答
1
投票

你正在寻找的功能是facet_wrap

创建一些虚拟数据:

NextRatings <- data.frame(year = rep(c(2001, 2019), 500),
                          rating.avg=rnorm(500))

line <- ggplot(NextRatings, aes(x=rating.avg)) + 
  geom_histogram(aes (y = ..density..), binwidth = .5, 
                 colour = "black", fill = "white") + 
  geom_density(alpha = .2, colour = "blue") + 
  facet_wrap("year")
line

enter image description here

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