如何在 R 中构建一个直方图,用多列二进制编码填充条形图?
How to build an histogram in R filling the bars with several columns binary coded?
我是 ggplot2 的新手,我想绘制每年(或 5 年)发表的文章数量的直方图以进行系统回顾。我有一个这样的 df:
Df <- data.frame( name = c("article1", "article2", "article3", "article4"),
date = c(2004, 2009, 1999, 2007),
question1 = c(1,0,1,0),
question2 = c(1,1,1,1),
question3 = c(1,1,1,1),
question4 = c(0,0,0,0),
question5 = c(1,0,1,0), stringsAsFactors = FALSE )
ggplot(Df, aes (date))+
geom_histogram(binwidth = 5, color= "black")
此外,对于直方图的每个条,我想用涵盖特定类型问题(问题 1 到 5,编码为 1 或 0,具体取决于问题是否存在)的文章数量填充条或缺席)。问题是我有 5 个问题,我想在一张图中显示出来。而且我不知道该怎么做...我尝试了 fill 参数并使用 geom_bar 但失败了。
非常感谢您的帮助
这是一个方法。这是一个带有 ggplot
.
的简单条形图
这类问题通常与重塑数据有关。格式应该是长格式,数据是宽格式。请参阅 this post 了解如何将数据从宽格式重塑为长格式。
library(dplyr)
library(tidyr)
library(ggplot2)
t %>%
select(-Code) %>%
pivot_longer(
cols = starts_with("Question"),
names_to = "Question"
) %>%
mutate(Publication_date = factor(Publication_date)) %>%
ggplot(aes(Publication_date, fill = Question)) +
geom_bar() +
xlab("Publication Date")
测试数据
set.seed(2021)
n <- 200
Code <- paste0("Article", 1:n)
Publication_date <- sample(2000:2020, n, TRUE)
Question <- replicate(5, rbinom(n, 1, 0.5))
colnames(Question) <- paste0("Question", 1:5)
t <- data.frame(Code, Publication_date)
t <- cbind(t, Question)
我是 ggplot2 的新手,我想绘制每年(或 5 年)发表的文章数量的直方图以进行系统回顾。我有一个这样的 df:
Df <- data.frame( name = c("article1", "article2", "article3", "article4"),
date = c(2004, 2009, 1999, 2007),
question1 = c(1,0,1,0),
question2 = c(1,1,1,1),
question3 = c(1,1,1,1),
question4 = c(0,0,0,0),
question5 = c(1,0,1,0), stringsAsFactors = FALSE )
ggplot(Df, aes (date))+
geom_histogram(binwidth = 5, color= "black")
此外,对于直方图的每个条,我想用涵盖特定类型问题(问题 1 到 5,编码为 1 或 0,具体取决于问题是否存在)的文章数量填充条或缺席)。问题是我有 5 个问题,我想在一张图中显示出来。而且我不知道该怎么做...我尝试了 fill 参数并使用 geom_bar 但失败了。
非常感谢您的帮助
这是一个方法。这是一个带有 ggplot
.
的简单条形图
这类问题通常与重塑数据有关。格式应该是长格式,数据是宽格式。请参阅 this post 了解如何将数据从宽格式重塑为长格式。
library(dplyr)
library(tidyr)
library(ggplot2)
t %>%
select(-Code) %>%
pivot_longer(
cols = starts_with("Question"),
names_to = "Question"
) %>%
mutate(Publication_date = factor(Publication_date)) %>%
ggplot(aes(Publication_date, fill = Question)) +
geom_bar() +
xlab("Publication Date")
测试数据
set.seed(2021)
n <- 200
Code <- paste0("Article", 1:n)
Publication_date <- sample(2000:2020, n, TRUE)
Question <- replicate(5, rbinom(n, 1, 0.5))
colnames(Question) <- paste0("Question", 1:5)
t <- data.frame(Code, Publication_date)
t <- cbind(t, Question)