簡體   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