1

我有一个不同物种和不同损害的数据集。正如您在我的数据中看到的那样,我的代码中只有两种不同的“损害”,但事实上,我得到了三种不同的“损害”。我想为每个物种(狼、熊和野猪)绘制我的数据。我想要用于损坏 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),但没有用。有没有其他人遇到过同样的问题?

4

2 回答 2

1

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

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)

在此处输入图像描述

于 2020-10-13T08:15:38.257 回答
0

一种选择是指定factor所有 s 的级别Damage,就像您对 s 所做的那样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 包(v0.3.0)于 2020 年 10 月 13 日创建

然后你可以放下scale_fill_discrete()

于 2020-10-13T08:26:18.407 回答