从 Excel 读取并绘制分组条形图

时间:2021-05-14 11:26:31

标签: r

我有一个 Excel 电子表格,可以用来查看谋杀案中受害者和罪犯之间的关系。凶手要么认识受害者,要么不认识。

enter image description here

我想将其绘制在条形图中,但我需要每年进行分组。我在 R 图形方面有点绿色,所以我做了一个我想要在我的报告中拥有的图像:

enter image description here

我有以下代码:

# Libraries
library("readxl")

res <- readxl::read_excel("muders_in_norway_with_relations.xlsx", sheet = 1)

dput(head(res[, 1:3])) 

# Plot bar
barplot(`Relation`~`2019`, res,
        main = "Murders in Norway with relations",
        xlab = "Year",
        ylab = "Murders")


输出这个:

## structure(list(Relation = c("Relations", "No relation"), `2019` = c(26, 
## 3), `2020` = c(30, 1)), row.names = c(NA, -2L), class = c("tbl_df", 
## "tbl", "data.frame"))

Maby 我在将数据读入 R 时做错了什么?

1 个答案:

答案 0 :(得分:1)

我是这样做的:

library(data.table)    
library(ggplot2)
a = matrix(c(26,30,3,1),ncol=2,byrow = T)
a= as.data.frame(a)
a$r = c('relation', 'no relation')
colnames(a )=c('2019','2020','r')
a= melt(a)
ggplot(a, aes(fill=r,x=variable,y=value))+
  geom_bar(stat="identity", position=position_dodge(), width = 0.5)+
  theme_classic()+
  scale_fill_manual(values = c('blue','red'))

也许就您而言,您可以这样做:

library("readxl")
library(data.table)
library(ggplot2)
res <- as.data.frame(readxl::read_excel("murders_in_norway_with_relations.xlsx", sheet = 1))
res$r = c('relation','No relation')
res=reshape::melt(res)
ggplot(res, aes(fill=r,x=variable,y=value))+
geom_bar(stat="identity", position=position_dodge(), width = 0.5)+
theme_classic()+
scale_fill_manual(values = c('blue','red'))

能胜任吗?

enter image description here

相关问题