【发布时间】:2020-10-10 12:59:36
【问题描述】:
我想使用 ggplot2 从 iris 数据集中绘制多个直方图。唯一缺少的是一种优雅的方法,可以将该数据集中的列名设置为labs (title = ) 中每个图的标题。我之前尝试过以多种方式使用colnames 和paste,但是,这并没有返回所需的输出。你们有谁知道如何完成最后一步,以便每个直方图将相应的列名显示为标题?
这是我的代表:
library (ggplot2)
# Reorder iris columns for convenience
df <- iris[,c(5, 1:4)]
# Histograms - z represents the columns of the df containing data for histograms
histograms <- apply (df[,2:ncol(df)], 2, function (z){
ggplot(df, aes(x = z)) +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, args = list(mean = mean(z, na.rm =TRUE), sd = sd(z, na.rm = TRUE)), colour = "blue") +
facet_wrap(~ Species) +
labs (title = "Histogram for column z", x = "values")
})
histograms
【问题讨论】: