首页 > 解决方案 > 向 geom_col 添加一个额外的钉书钉,值为 0 R

问题描述

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

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),但没有用。有没有其他人遇到过同样的问题?

标签: rggplot2aesscalegeom

解决方案


在带有计数的条形顶部添加文本会起作用吗?

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)

在此处输入图像描述


推荐阅读