我正在尝试让aa函数为不同的群体生成大量的(垂直)条形图,这些条形图按四分位数表示收入均值。我希望我的四分位数列在数据帧中使用它们的列名来单独命名。
这使得我的测试数据:
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")发布于 2017-12-10 12:30:25
不知道为什么你认为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")

https://stackoverflow.com/questions/47734488
复制相似问题