更改ggplot上的geom_bar宽度

Fbj*_*506 5 r ggplot2

我正在制作一个条形图,显示返回嵌套的不同类型的猎物的百分比。

我的数据如下:

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)

我的条形不再按正确的顺序排列,或按“猎物”分组。有什么办法可以改变吗? 在此处输入图片说明

Uwe*_*Uwe 3

通过在绘图之前使用tableprop.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()
  • 并用作( 的 2.2.0 版本引入的新函数)geom_col的简写。geom_bar(stat = "identity")ggplot2