【问题标题】:Grouped bar plot in R [closed]R中的分组条形图[关闭]
【发布时间】:2017-07-16 12:15:38
【问题描述】:

对于 R 中的以下 data.frame,我将如何制作按Treatment Type 分组的条形图?每个条的高度将代表Number of OccurrencesSpecies ASpecies B 将是两个相互相邻的独立条形图。

`Treatment Type`      Species    `Number of Occurrences`
         <chr>         <chr>                    <dbl>
Treatment           Species A                    10
Control             Species A                    15
Treatment           Species B                    55
Control             Species B                     5

【问题讨论】:

  • 我看到一个数字变量和两个潜在的分组变量。您能详细说明您希望实现的条形图吗?
  • 请勿将您的数据发布为图片,请了解如何提供reproducible example。此外,还请阅读:How to Ask
  • @KarstenW。我们被要求使用这些信息在 R 中制作一个分组条形图。感谢您的快速回复!
  • @Sahar 您必须始终提供可重现的示例。

标签: r dataframe data-visualization


【解决方案1】:

假设“组”,你的意思是二进制变量Type,我有以下两种解决方案,分别使用latticeggplot2包:

在绘图之前,我重构了一个(有限版本的?)您的数据:

df <- data.frame(
  Type = rep(c("Treatment", "Control"), 2),
  Species = c(rep("Species A", 2), rep("Species B", 2)),
  Number_of_Occurrences = c(10, 15, 55, 5)
)
df
# Type   Species Number_of_Occurrences
# 1 Treatment Species A                    10
# 2   Control Species A                    15
# 3 Treatment Species B                    55
# 4   Control Species B                     5

第一种方法:lattice包:

library(lattice)
barchart(
  Number_of_Occurrences~Species,
  data=df, groups=Type, 
  scales=list(x=list(rot=90,cex=0.8))
)

第二种方法,ggplot2包;您需要使用reshape::melt 函数重新格式化data.frame 以满足ggplot2 的要求

library(reshape)
library(ggplot2)
df.m <- melt(df)
df.m
# Type   Species              variable value
# 1 Treatment Species A Number_of_Occurrences    10
# 2   Control Species A Number_of_Occurrences    15
# 3 Treatment Species B Number_of_Occurrences    55
# 4   Control Species B Number_of_Occurrences     5
ggplot(df.m, aes(Species, value, fill = Type)) + 
  geom_bar(stat="identity", position = "dodge")

参考:this Stack Overflow post

【讨论】:

  • 谢谢!!!我用了格子包。当我尝试进入并添加 x 并更改 y 标签时,它不会让我这样做。我用过 xlab 和 ylab。
  • 这对我有用:barchart( Number_of_Occurrences~Species, data=df, groups=Type, xlab = "Species", ylab="Number of Occurrences", scales=list(x=list(rot=90,cex=0.8)) )
  • 如果您决定使用ggplot2,请附加xlab()ylabggplot(df.m, aes(Species, value, fill = Type)) + geom_bar(stat="identity", position = "dodge") + ylab("Number of Occurrences")
  • 谢谢!我使用了格子包。我还有一个问题(对不起所有这些问题!)。如果我需要制作三种不同哺乳动物顺序的平均值的条形图,我将如何在 R 中做到这一点?我尝试了我能想到的一切。我计算了所有这些的平均值,但我不知道从那里去哪里。
  • 您可以创建一个带有mean 列和/或其他汇总统计信息的data.frame。然后,像以前一样使用其中一种 barplot 方法绘制这个新的 data.frame。如果您不熟悉如何制作 data.frames,请查看此帖子 r-tutor.com/r-introduction/data-frame
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 2016-07-11
相关资源
最近更新 更多