【问题标题】:hist() main title from list namehist() 来自列表名称的主标题
【发布时间】:2020-08-04 12:40:51
【问题描述】:

我正在从一个列表中绘制 7 个直方图,并希望根据列表的位置更新直方图的标题。

这是我目前得到的,但在执行脚本时出现以下错误。

item_df[df] 中的错误:无效的下标类型“列表”

full_df <- read.csv("filename")

item_df <- split(full_df, full_df$PIA_ITEM)

par(mfrow = c(3,3)) # 3 rows and 3 columns
for (df in item_df) {
  hist(df[[7]], breaks=9,  main = paste("Histogram of", names(item_df[df])))
}

错误点在于我尝试使用循环索引来绘制列表名称位置

main = paste("Histogram of", names(item_df[df]))

【问题讨论】:

    标签: r histogram


    【解决方案1】:

    由于未提供数据,我添加了一个带有虚拟数据的示例,然后为您的问题添加了一个可能的草图。根据您的代码,我认为您正在尝试将 PIA_ITEM 的值添加为标题并将变量绘制在位置 7。这个虚拟示例适用于 iris:

    full_df <- iris
    
    item_df <- split(full_df, full_df$Species)
    
    par(mfrow = c(3,3)) # 3 rows and 3 columns
    for (i in 1:length(item_df)) 
    {
      hist(item_df[[i]]$Sepal.Length, breaks=9,  
           main = paste("Histogram of", unique(item_df[[i]]$Species)),
           xlab = 'x')
    }
    

    并产生:

    你的问题的代码应该是这样的:

    full_df <- read.csv("filename.csv")
    
    item_df <- split(full_df, full_df$PIA_ITEM)
    
    par(mfrow = c(3,3)) # 3 rows and 3 columns
    for (i in 1:length(item_df)) 
    {
      hist(item_df[[i]][,7], breaks=9,  
           main = paste("Histogram of", unique(item_df[[i]]$PIA_ITEM)),
           xlab = 'x')
    }
    

    【讨论】:

      【解决方案2】:

      改编这个例子:

      item_df <- split(mtcars[, 1], mtcars$cyl)
      
      par(mfrow = c(1, 3))
      for (i in names(item_df)){
        hist(item_df[[ i ]], main = paste("Histogram of", i))
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-13
        • 2016-05-20
        • 1970-01-01
        • 1970-01-01
        • 2018-05-14
        • 1970-01-01
        • 1970-01-01
        • 2017-03-06
        相关资源
        最近更新 更多