首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ggplot2:用于连续数据的具有垂直柱的条形图

ggplot2:用于连续数据的具有垂直柱的条形图
EN

Stack Overflow用户
提问于 2017-12-10 07:57:43
回答 1查看 459关注 0票数 1

我正在尝试让aa函数为不同的群体生成大量的(垂直)条形图,这些条形图按四分位数表示收入均值。我希望我的四分位数列在数据帧中使用它们的列名来单独命名。

这使得我的测试数据:

代码语言:javascript
运行
复制
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值吗?

代码语言:javascript
运行
复制
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")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-10 12:30:25

不知道为什么你认为ggplot2想要宽格式的数据。从来都不是这样的。一旦你转换成长格式,并对你的绘图函数做了一些更改,事情就会很好地工作。

这是来自你的代码,没有改变:

代码语言:javascript
运行
复制
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)

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

代码语言:javascript
运行
复制
# 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")

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47734488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档