【问题标题】:ggplot barplot graph same size for different groupsggplot barplot 图不同组的大小相同
【发布时间】:2019-03-06 00:54:18
【问题描述】:

我正在尝试在多个月内为三种须鲸物种创建一个条形图。我的问题是,酒吧的大小在几个月之间会发生变化,因为有几个月没有看到其中一种物种。知道如何解决这个问题吗?

我使用这个代码:

land_based_individuals <- read.csv("Land_based_sightings_antero.csv", 
                                   header = T, sep =",", dec =",", stringsAsFactors = F)

land_based_individuals_month <- aggregate(land_based_individuals$sightings, 
                                          by = list(land_based_individuals$Month, land_based_individuals$Species), 
                                          FUN=sum)

colnames(land_based_sightings_month)[1] <- "Month"
colnames(land_based_sightings_month)[2] <- "Species"
colnames(land_based_sightings_month)[3] <- "Sightings"

library (ggplot2)

ggplot(land_based_sightings_month, 
       aes(fill=Species, y=Sightings, x=land_based_sightings_month$Month)) +  
  geom_bar(position="dodge", stat="identity") +
  ggtitle("Land-based Sightings per month")+ xlab("Month")+ ylab("Sightings")+  
  scale_x_continuous("Month", labels = as.character(land_based_sightings_month$Month), 
                     breaks = land_based_sightings_month$Month)+  
  ggsave(file="Land-based Sightings per month.png",  
         width = 14, height = 9, dpi = 120)

这是我从data得到的条形图

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您可以使用tidyr::complete 补齐缺少的Month-Species 与0 的组合。

library(tidyverse)
land_based_individuals %>%
    group_by(Month, Species) %>%
    summarise(Sightings = sum(Sightings)) %>%
    complete(Month, Species, fill = list(Sightings = 0)) %>%
    ggplot(aes(Month, Sightings, fill = Species)) +
        geom_col(position = "dodge2") +
        ggtitle("Land-based Sightings per month") +
        xlab("Month") +
        ylab("Sightings")

我还清理了您的代码,其中包含一些(次要)代码和格式问题。最重要的是,永远不要在aes 中使用$-indexing 在ggplot 中;这可能会在使用时导致一些令人讨厌和意想不到的结果,例如方面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多