Changing geom_bar width to ggplot

I am making a bar graph showing the percentage of different types of victim items returned to the nest.

My data is as follows:

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")

My schedule is as follows.

enter image description here

I would like all the widths of the type columns to be the same, but when I change the width under geom_bar, it changes the width of the "victim" strip. When I try to use the following:

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")

My bars are no longer in the correct order or grouped by "Prey". Is there any way to change this? enter image description here

+4
source share
1 answer

table prop.table , Prey Type. .

, , .

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")

enter image description here

table(Preydata$Prey, Preydata$Type) Prey Type, , :

             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

prop.table . (..count..)/sum(..count..) OP.

- , , ggplot, .

plot OP, ,

  • Freq (..count..)/sum(..count..) ,
  • fill ggplot(),
  • geom_col short-hand geom_bar(stat = "identity") ( , 2.2.0 ggplot2).
+2

Source: https://habr.com/ru/post/1668455/


All Articles