如何使ggplot2在数据子集上保持未使用的级别

时间:2017-03-20 02:31:01

标签: r plot ggplot2 bar-chart levels

我的问题显然不是新问题,但我无法找到我的确切编码问题。我正在处理我的一部分数据(可用here),并且一直在尝试scale_x_discrete(drop=FALSE)scale_fill_discrete(drop=FALSE)的所有可能组合,以尝试让ggplot2包含一个空格条形图将用于花栗鼠(n = 0表示事件“CF” - nb 这对应于数据中的变量“forage”。)

我使用的代码如下:

require(ggplot2)
library(ggthemes)

#excluding MICROs from my plot
ggplot(data[data$sps=="MAMO" | data$sps=="TAST" | data$sps=="MUVI"|    data$sps=="MUXX" | data$sps=="TAHU",], 
      aes(sps, fill=forage))+geom_bar(position="dodge") +
    labs(x = "Species", y = "Number of observations") +
    scale_x_discrete(labels = c("Marmot","American Mink", "Weasel Spp.", "Red squirrel", "Chipmunk")) +
    theme_classic() + 
    scale_fill_manual(values = c("#000000", "#666666", "#999999","#CCCCCC"), name = "Event")

然后我得到一个像这样的情节: Plot

当我添加scale_x_discrete(drop = FALSE)时,我明白这一点:Problem Plot 该代码似乎正在做的是包括我之前排除的MICRO数据(因此在土拨鼠和花栗鼠仍然只有3个小节之后,所有内容都会移动一个)。

当我尝试scale_fill_discrete(drop = FALSE)时,结果图从第一张图中完全没有变化。当我同时尝试scale_x_discrete(drop = FALSE)scale_fill_discrete(drop = FALSE)时,情节看起来就像第二个情节。

我想我可以手动去制作一个包含每个级别(事件)频率的小表,但我想首先尝试在R中正确编码。

有人对我在代码中添加/更改内容有什么建议吗?

更新 我尝试了下面建议的代码:

df1 %>% 
  filter(sps != "MICRO") %>% 
  group_by(sps) %>% 
  count(forage) %>% 
  ungroup %>% 
  complete(sps, forage, fill = list(n = 0)) %>% 
ggplot(aes(sps, n)) + geom_col(aes(fill = forage), position = "dodge") +
  scale_x_discrete(labels=c("Marmot","American Mink", "Weasel Spp.", "Red squirrel", "Chipmunk")) + 
  theme_classic() + 
  scale_fill_manual(values=c("#000000", "#666666", "#999999","#CCCCCC"), name = "Event") + 
  labs(x = "Species", y = "Number of observations")

得到的情节有空间(耶!)但仍然有一个空格,用于MICRO的位置:

second attempt

1 个答案:

答案 0 :(得分:2)

这里的问题是没有为sps = TAST,forage = CF生成零计数。您可以使用tidyr::complete创建该计数。我还添加了一些dplyr函数来使代码更清晰。假设您的数据框名为df1(而不是data,这是一个基本函数名称,因此不是一个好选择):

更新:使用stringsAsFactors = FALSE解决评论中的问题。

library(dplyr)
library(tidyr)
library(ggplot2)

df1 <- read.table("data.txt", header = TRUE, stringsAsFactors = FALSE)
df1 %>% 
  filter(sps != "MICRO") %>% 
  group_by(sps) %>% 
  count(forage) %>% 
  ungroup %>% 
  complete(sps, forage, fill = list(n = 0)) %>% 
  ggplot(aes(sps, n)) + geom_col(aes(fill = forage), position = "dodge") +
    scale_x_discrete(labels=c("Marmot","American Mink", "Weasel Spp.", "Red squirrel", "Chipmunk")) + 
    theme_classic() + 
    scale_fill_manual(values=c("#000000", "#666666", "#999999","#CCCCCC"), name = "Event") + 
    labs(x = "Species", y = "Number of observations")

结果: enter image description here