【问题标题】:How to Create comparison bar graph如何创建比较条形图
【发布时间】:2018-08-19 01:21:21
【问题描述】:

我在下面提到了数据帧:

Month    Fig1    Fig2
Mar-17   10      12
Feb-17   25      18
Jan-17   10      15
Dec-16   11      18
Nov-16   10      15

我想为此创建一个彩色条形图,我尝试过下面提到的代码,但没有成功。

bargraph <- ggplot(data = df1) +
  geom_bar(aes(x = Month,
                y = value,
                group = variable,
                color = variable)) +
  theme(legend.title=element_blank())

此外,我想将该图表存储在JPGPNG 中,以便通过mailR 发送。

【问题讨论】:

    标签: r dataframe ggplot2 geom-bar


    【解决方案1】:

    概述

    df 转换成一个宽矩阵——df$Month 中的每个值一列,每个非df$Month 列一列——在barplot() 内部使用它之前。

    由于df$Month 以缩写的月-年格式给出, 包中的as.yearmon() 函数用于在绘图之前按时间顺序对矩阵进行排序。

    可重现的示例

    # load necessary packages
    library( zoo )
    
    # load data
    df <-
      read.table(
        text = "Month    Fig1    Fig2
    Mar-17   10      12
        Feb-17   25      18
        Jan-17   10      15
        Dec-16   11      18
        Nov-16   10      15"
        , header = TRUE
        , stringsAsFactors = FALSE
      )
    
    # create complementary color scheme
    color.scheme <- c( "#18A4D2", "#D24618" )
    
    # store non-Month column indices
    non.month.column.condition <-
      which( !colnames( df ) %in% "Month" )
    
    # transfrom Month to a 
    # yearmon class using the zoo package
    df$Month <- 
      as.yearmon( x = df$Month, format = "%b-%y" )
    
    # reorder the data frame by 
    # chronological order
    df <-
      df[ order( df$Month ), ]
    
    # transform df
    # to wide matrix
    # one column for each value in df$Month
    month.values.by.fig <-
      lapply(
      X = df[ , non.month.column.condition ]
      , FUN = function( i )
        tapply(
          X = i
          , INDEX = df$Month
          , FUN = function( j )
            j
        )
    )
    
    # collapse values into one matrix
    month.values.by.fig <-
      do.call(
        what = "rbind"
        , args = month.values.by.fig
      )
    
    # plot and save the results
    png(
      filename = "fig_value_by_month.png"
      , units = "px"
      , height = 1600
      , width = 2400
      , res = 300
    )
    barplot(
      height = month.values.by.fig
      , beside = TRUE
      , col = color.scheme
      , border = NA
      , legend.text = TRUE
      , args.legend = list(
        x = "topleft"
        , bty = "n"
        , border = NA
      )
      , las = 1
      , ylim = c( 0, 30 )
      , xlab = "Month-Year"
      , ylab = "Values"
      , main = "Values Over Time, by Figure Type"
    )
    # shut down plot device
    dev.off()
    
    # end of script #
    

    【讨论】:

    • 您已经硬编码了ylim = c( 0, 30 ) 的值,但它可以是基于数据帧的任何内容。??
    • @Rahulshah, ylim 设置 y 轴的最小和最大限制。随意根据数据将其更改为您想要的任何内容,例如ylim = c( 0, max( month.values.by.fig ) )
    【解决方案2】:

    我已将您的代码修改如下。

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    df2 <- df1 %>% 
      gather(Fig, Value, -Month) %>%
      mutate(Month = factor(Month, 
                            levels = c("Nov-16", "Dec-16", "Jan-17", "Feb-17", "Mar-17"))) %>%
      arrange(Month)
    
    bargraph <- ggplot(data = df2) +
      geom_bar(aes(x = Month,
                   y = Value,
                   fill = Fig,
                   color = Fig),
               stat = "identity",
               position = position_dodge()) +
      theme(legend.title=element_blank())
    bargraph
    

    要使用ggplot2 绘制组条形图,我们需要将df1 从宽格式转换为长格式,如df2。然后,有必要对 Month 列重新排序,因为这决定了 x 轴上的顺序。因此,我将Month 列转换为因子并使用arrange 对其进行重新排序。

    geom_bar中,我们需要指定stat = "identity"position = position_dodge()。可以使用geom_col 在没有stat = "identity" 的情况下创建相同的绘图。

    要保存绘图,我们可以使用ggsave 函数。您可以在filename 参数中指定文件目录。

    ggsave(filename = "bargraph.jpg", plot = bargraph)
    

    最后,使用 确实是一个完全不同的问题。请在 Stack Overflow 上搜索相关问题。如果您找不到您需要的信息,那么您可以考虑提出一个新问题。

    数据

    df1 <- read.table(text = "Month    Fig1    Fig2
    'Mar-17'   10      12
                      'Feb-17'   25      18
                      'Jan-17'   10      15
                      'Dec-16'   11      18
                      'Nov-16'   10      15",
                      header = TRUE, stringsAsFactors = FALSE)
    

    【讨论】:

    • 收到此错误:Error in eval(expr, envir, enclos) : object 'Value' not found
    • @Rahulshah 我无法重现此错误。请确保您加载了我在示例中指定的所有包。
    • 谢谢...它成功了。只是想知道为什么png 图像没有显示在 gmail 中。
    • 我认为这是因为它的大小如何保持图形大小(即高度和宽度)很小。
    猜你喜欢
    • 2019-04-10
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2019-09-01
    • 2021-12-28
    • 2015-05-29
    相关资源
    最近更新 更多