繁体   English   中英

如何在 ggplot2 中将列名设置为直方图标题

[英]How to set column names as histogram titles in ggplot2

我想使用ggplot2从 iris 数据集中绘制多个直方图。 唯一缺少的是一种优雅的方法,可以将该数据集中的列名设置为labs (title = )中每个 plot 的标题。 我之前尝试使用colnames并以多种方式paste ,但是,这并没有返回所需的 output。 你们有谁知道如何完成最后一步,以便每个直方图将相应的列名显示为标题?

这是我的代表:

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

尝试这个。 而不是对列进行迭代,而是对名称进行迭代:

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 <- lapply (names(df[,2:ncol(df)]), function (z){
  mean <- mean(df[[z]], na.rm =TRUE)
  sd <- sd(df[[z]], na.rm =TRUE)
  ggplot(df, aes(x = !!sym(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") +
    stat_function(fun = dnorm, args = list(mean = mean, sd = sd), colour = "blue") +
    facet_wrap(~ Species) +
    labs (title = paste0("Histogram for column ", z), x = "values")
})

histograms[[1]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

代表 package (v0.3.0) 于 2020 年 6 月 20 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM