【问题标题】:How to set column names as histogram titles in ggplot2如何在ggplot2中将列名设置为直方图标题
【发布时间】:2020-10-10 12:59:36
【问题描述】:

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

这是我的代表:

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

【问题讨论】:

标签: r ggplot2


【解决方案1】:

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

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`.

reprex package (v0.3.0) 于 2020-06-20 创建

【讨论】:

  • 这是一个不错的解决方案!感谢您提供有用的意见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
相关资源
最近更新 更多