我正在制作一个条形图,显示返回嵌套的不同类型的猎物的百分比。
我的数据如下:
Prey <- c(rep("Bird", 12), rep("Lizard", 3), rep("Invertebrate", 406))
Type <- c(rep("Unknown bird", 12), rep("Skink", 2), rep("Gecko", 1),
rep("Unknown Invertebrate", 170), rep("Beetle", 1),
rep("Caterpillar", 3), rep("Grasshopper", 3), rep("Huhu grub", 1),
rep("Moth", 34), rep("Praying mantis", 1), rep("Weta", 193))
Preydata <- data.frame(Prey,Type)
ggplot(Preydata, aes(x = Prey, y = (..count..)/sum(..count..))) +
scale_y_continuous(labels = percent_format()) +
geom_bar(aes(fill = Type), position = "dodge")
Run Code Online (Sandbox Code Playgroud)
我的图形如下图所示。
我希望所有“类型”栏的宽度都相同,但是当我更改其下的宽度时geom_bar,只会更改“猎物”栏的宽度。当我尝试使用以下内容时:
ggplot(Preydata, aes(x = as.numeric(interaction(Prey, Type)),
y = (..count..)/sum(..count..))) +
scale_y_continuous(labels = percent_format()) +
geom_bar(aes(fill = Type), position = "dodge")
Run Code Online (Sandbox Code Playgroud)
通过在绘图之前使用table和prop.table准备数据,可以确保包括和的所有可能组合。这会强制条形具有相同的宽度,而不改变条形的顺序。PreyType
因此,这是使用交互或绑定已标记为重复的缺失组合的替代方法 。
Preydata2 <- as.data.frame(prop.table(table(Preydata$Prey, Preydata$Type)))
names(Preydata2) <- c("Prey", "Type", "Freq")
library(ggplot2)
library(scales)
ggplot(Preydata2, aes(x = Prey, y = Freq, fill = Type)) +
scale_y_continuous(labels = percent_format()) +
geom_col(position = "dodge")
Run Code Online (Sandbox Code Playgroud)
产生
table(Preydata$Prey, Preydata$Type)创建和的所有组合的列联表,甚至是基础数据中未出现的那些组合:PreyType
Beetle Caterpillar Gecko Grasshopper Huhu grub Moth Praying mantis Skink Unknown bird
Bird 0 0 0 0 0 0 0 0 12
Invertebrate 1 3 0 3 1 34 1 0 0
Lizard 0 0 1 0 0 0 0 2 0
Unknown Invertebrate Weta
Bird 0 0
Invertebrate 170 193
Lizard 0 0
Run Code Online (Sandbox Code Playgroud)
prop.table将计数转换为分数。这相当于(..count..)/sum(..count..)OP中的内容。
数据准备的最后一步是将表转换为数据框(所需的格式)ggplot,并适当地重命名列。
绘图命令与 OP 类似,除了
Freq使用 已经计算的值而不是(..count..)/sum(..count..)动态计算,fill已经转移到最初的呼吁ggplot(),geom_col的简写。geom_bar(stat = "identity")ggplot2| 归档时间: |
|
| 查看次数: |
1425 次 |
| 最近记录: |