向 geom_col 添加一个值为零 R 的附加订书钉

Add an additional staple to geom_col with value zero R

我有一个不同物种和不同损害的数据集。正如您在我的数据中看到的那样,我的代码中只有两种不同的“损坏”,但事实上,我得到了三种不同的“损坏”。我想绘制我的数据和每个物种(狼、熊和野猪)的数据。我想要 damage1(放牧)、damage2(踩踏)和 damage3 等的订书钉。但我希望 damage3 的订书钉为“零”。我想以某种方式表明 damage3 中的物种为零。

data <- data.frame(Species=c("Wolf", "Wolf", "Bear", "Bear", "Woldboar", "Wolf", "Wolf", "Bear", "Bear", "Wildboar"), Damage=c(rep("Grazing", 5),rep("Stomp", 5)))


data$Species<- factor(data$Species, levels=c("Wolf","Bear", "Wildboar"))

data <- data.frame(table(data))

ggplot(data) + 
  aes(x = Species, y = Freq, fill = Damage) + 
  geom_col(position = "dodge2", col = "black") + 
  ylab("Count") + 
  xlab("Species") + 
  theme_classic() +
  scale_x_discrete(drop = FALSE) +
  theme(legend.position = "top") +
  scale_fill_discrete(labels = c("Grazing", "Stomp", "Fear"), drop = FALSE)

我试过 scale_fill_discrete(drop = FALSE),但没用。有没有其他人遇到过同样的问题?

在带有计数的条形顶部添加文本是否可行?

library(ggplot2)

ggplot(data) + 
  aes(x = Species, y = Freq, fill = Damage, label = Freq) + 
  geom_col(position = "dodge2", col = "black") + 
  ylab("Count") + 
  xlab("Species") + 
  geom_text(position = position_dodge(width = 1), vjust = -0.5, size = 5) +
  theme_classic() +
  scale_x_discrete(drop = FALSE) +
  theme(legend.position = "top") +
  scale_fill_discrete(labels = c("Grazing", "Stomp", "Fear"), drop = FALSE)

一个选项是指定所有 Damagefactor 级别,就像您为 Species:

所做的一样
library(tidyverse)

data <- data.frame(Species=c("Wolf", "Wolf", "Bear", "Bear", "Woldboar", "Wolf", "Wolf", "Bear", "Bear", "Wildboar"), Damage=c(rep("Grazing", 5),rep("Stomp", 5)))

data$Species<- factor(data$Species, levels=c("Wolf","Bear", "Wildboar"))

# Set factor levels for damages, adding in a third level (Fear)
data$Damage<- factor(data$Damage, levels=c("Grazing","Stomp", "Fear"))

data <- data.frame(table(data))

ggplot(data) + 
  aes(x = Species, y = Freq, fill = Damage) + 
  geom_col(position = "dodge2", col = "black") + 
  ylab("Count") + 
  xlab("Species") + 
  theme_classic() +
  scale_x_discrete(drop = FALSE) +
  theme(legend.position = "top")

reprex package (v0.3.0)

于 2020-10-13 创建

然后您可以删除 scale_fill_discrete()