【问题标题】:ggplot2: Bar graph with vertical columns for continuous dataggplot2:具有连续数据垂直列的条形图
【发布时间】:2017-12-09 23:57:43
【问题描述】:

我正在尝试制作一个函数来生成大量(垂直)条形图,以按四分位数为各个组生成收入均值。我希望我的四分位列在数据框中使用它们的列名单独命名。

这使得我的测试数据:

quart_nms <- c("1st", "2nd", "3rd", "4th")
tile_nms <- function(vec, nms){
  if (length(vec) != length(nms)) stop(
    "length vec ", length(vec), " must equal length nms ", length(nms))
  out <- data.frame(t(unlist(vec)))
  colnames(out)<- nms
  out
}
t1 <- tile_nms(1:4, quart_nms)

这是我的功能。我认为,我理解 ggplot2 需要此类图表的宽格式数据,但我怀疑我没有正确传递变量列表。它们不应该是 y 值吗?

bar_plot <- function(.dt, .tit="U.S. Personal Income Distribution by Quartile",
                     .sub = NULL, .xl = "Income Quartiles", .yl = "Mean Income", 
                     ...){
  ggplot(data =.dt) + 
    geom_col(mapping = aes(y = list(1st, 2nd, 3rd, 4th)), stat = identity) +
    labs(title = .tit, subtitle = .sub)
}

gr1 <- bar_plot(.dt = t1, .sub = "pop subgroup name")

【问题讨论】:

    标签: r debugging ggplot2 graphics


    【解决方案1】:

    不知道为什么你认为 ggplot2 需要宽格式的数据。从来都不是这样。一旦您转换成长格式并对绘图功能进行一些更改,一切都会正常工作。

    这是来自您的代码,未更改:

    quart_nms <- c("1st", "2nd", "3rd", "4th")
    tile_nms <- function(vec, nms){
      if (length(vec) != length(nms)) stop(
        "length vec ", length(vec), " must equal length nms ", length(nms))
      out <- data.frame(t(unlist(vec)))
      colnames(out)<- nms
      out
    }
    t1 <- tile_nms(1:4, quart_nms)
    

    以下是我的代码,基于你的:

    # needed libraries
    library(tidyr)
    library(ggplot2)
    
    # convert to long format
    tlong <- gather(t1, quartile, value)
    tlong$quartile <- factor(tlong$quartile, levels = quart_nms) # make factor and put levels in the right order
    
    # plotting function
    bar_plot <- function(.dt, .tit="U.S. Personal Income Distribution by Quartile",
                         .sub = NULL, .xl = "Income Quartiles", .yl = "Mean Income", 
                         ...){
      ggplot(data =.dt) + 
        geom_col(mapping = aes(x = quartile, y = value)) +
        labs(title = .tit, subtitle = .sub, x = .xl, y = .yl)
    }
    
    # call plotting function with long-format data
    bar_plot(.dt = tlong, .sub = "pop subgroup name")
    

    【讨论】:

    • 谢谢克劳斯!这太壮观了。我想我有一些例子说连续变量的条形图需要宽格式,也许在非常旧的 ggplot2 版本中是真的?或者也许我梦见了他们。
    猜你喜欢
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多