如何使用 R 中的数据帧列表编写箱线图函数

发布于 2025-01-09 13:40:07 字数 2458 浏览 0 评论 0原文

在下面的数据框中,

set.seed(123)
code <- c(5001,5001,5250,5250,5425,5425,5610,5610,5910,5910,5010,5010,6110,6110,6135,6135,6220,6220,6550,6550)
county <- c("A01","A01","A01","A02","A01","A02","A03","A03","A01","A02","A03","A04","A01","A01","A01","A01","A01","A01","A02","A02")
state <- c("PA","PA","NY","NY","DE","DE","PA","PA","NY","NY","PA","PA","NY","NY","DE","DE","PA","PA","NY","NY")
dept <- c("energy",'energy','edu','hous','hous','edu','energy','energy','hous','hous','edu','hous','hous','energy','energy',"energy",'energy','edu','hous','hous')
year <- c(2001,2001,2001,2001,2001,2002,2002,2002,2002,2002,2003,2003,2003,2003,2003,2004,2004,2004,2004,2004)
corp_tax <- runif(20, min=5, max=200)
income_tax <- runif(20, min=4, max=175)
bonus <- runif(20, min=10, max=211)
length(dept)
df <- data.frame(code, state, county, year,dept,corp_tax,income_tax,bonus)
df

# for each year 
subset(df,year == 2001)

我需要帮助编写一个用户定义函数,该函数接收数据框并执行以下操作:

(1)。选择 yearstatedeptcorp_tax

(2)。对于每个中的每个唯一的,绘制按部门分组的corp_tax箱线图。例如,对于 2001 年,我们将分别绘制 PANYDE 的箱线图。

(3)。将绘图(每页 2 个数字)导出为 pdf

请参阅下面的我的尝试:

library(ggplot2)
library(dplyr)

boxplotter <-function(data){

    #  select the columns
    new_data <-data%>%select(year,state,dept,corp_tax)
    
    #  split the data based on unique years 
    split_data <-split(new_data,new_data$year)
    
    # set the pdf for the plot
    pdf("boxplotter.pdf", 7, 5)
    #################This where I need help with the most, the looping process#####################
    # Looping through each state in each year 
    for (i in seq(1, length(unique(split_data$state)), 10)){
        
        # the actual plot
        ggplot(split_data, aes(x=dept, y=corp_tax)) + geom_boxplot(outlier.colour="red", outlier.shape=8,outlier.size=4) +
        scale_y_continuous(limits=c(0, max(split_data$corp_tax, na.rm=TRUE))) +
        scale_x_continuous(limits=c(0, max(split_data$corp_tax))) 
    dev.off()
}
#testing my function
boxplotter(df)

所需的输出应如下所示:

在此处输入图像描述

我愿意接受其他方法,请分享您的代码。谢谢!!

In the dataframe below

set.seed(123)
code <- c(5001,5001,5250,5250,5425,5425,5610,5610,5910,5910,5010,5010,6110,6110,6135,6135,6220,6220,6550,6550)
county <- c("A01","A01","A01","A02","A01","A02","A03","A03","A01","A02","A03","A04","A01","A01","A01","A01","A01","A01","A02","A02")
state <- c("PA","PA","NY","NY","DE","DE","PA","PA","NY","NY","PA","PA","NY","NY","DE","DE","PA","PA","NY","NY")
dept <- c("energy",'energy','edu','hous','hous','edu','energy','energy','hous','hous','edu','hous','hous','energy','energy',"energy",'energy','edu','hous','hous')
year <- c(2001,2001,2001,2001,2001,2002,2002,2002,2002,2002,2003,2003,2003,2003,2003,2004,2004,2004,2004,2004)
corp_tax <- runif(20, min=5, max=200)
income_tax <- runif(20, min=4, max=175)
bonus <- runif(20, min=10, max=211)
length(dept)
df <- data.frame(code, state, county, year,dept,corp_tax,income_tax,bonus)
df

# for each year 
subset(df,year == 2001)

I need help writing a user defined function that takes in a dataframe and does the following:

(1). select year, state,dept, corp_tax columns

(2). for each unique state in each year, plot boxplot for corp_tax grouped by dept. Example, for the year 2001, we will have boxplots for PA,NY and DE respectively.

(3). export the plots (2 figures per page) in pdf

See below for my attempt:

library(ggplot2)
library(dplyr)

boxplotter <-function(data){

    #  select the columns
    new_data <-data%>%select(year,state,dept,corp_tax)
    
    #  split the data based on unique years 
    split_data <-split(new_data,new_data$year)
    
    # set the pdf for the plot
    pdf("boxplotter.pdf", 7, 5)
    #################This where I need help with the most, the looping process#####################
    # Looping through each state in each year 
    for (i in seq(1, length(unique(split_data$state)), 10)){
        
        # the actual plot
        ggplot(split_data, aes(x=dept, y=corp_tax)) + geom_boxplot(outlier.colour="red", outlier.shape=8,outlier.size=4) +
        scale_y_continuous(limits=c(0, max(split_data$corp_tax, na.rm=TRUE))) +
        scale_x_continuous(limits=c(0, max(split_data$corp_tax))) 
    dev.off()
}
#testing my function
boxplotter(df)

Desired output should look like this :

enter image description here

I am open to other approaches, please share your code. Thanks!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄情伤 2025-01-16 13:40:07

这是一个解决方案。
拆分数据时,在同一条指令中按yearstate进行拆分。然后循环遍历分割列表,绘制每个数据集。使用ggave保存。

在下面的函数中,输出文件名取决于年份/州的组合,并且我包含了一个参数 verbose ,该参数在文件名写入磁盘时打印文件名。

library(ggplot2)

boxplotter <- function(X, file = "boxplotter%s.pdf", width = 7, height = 5, verbose = FALSE){
  # create a list of data.frame's by year and state
  year_list <- split(X, list(X[["year"]], X[["state"]]), sep = "_")
  # remove from the list the empty sub-lists. This is needed
  # because there might be combinations of year/state not
  # present in the input data and 'split' will create them 
  # anyway
  year_list <- year_list[sapply(year_list, nrow) > 0L]
  
  # loop with an index into the list to make it possible
  # to get the data and also the names attribute, used
  # to form the output filenames
  for(i in seq_along(year_list)){
    # work with a copy, this just makes the code that
    # follows easier to read
    Y <- year_list[[i]]
    # plot and save the plot
    filename <- sprintf(file, names(year_list)[i])
    g <- ggplot(Y, aes(x=dept, y=corp_tax)) + 
      geom_boxplot(outlier.colour="red", outlier.shape=8,outlier.size=4) +
      scale_y_continuous(limits=c(0, max(Y$corp_tax, na.rm=TRUE)))
    ggsave(filename, plot = g, device = "pdf", width = width, height = height)
    # want to see what was written to disk?
    if(verbose){
      msg <- paste("output file:", filename)
      message(msg)
    }
  }
  # return nothing
  invisible(NULL)
}

boxplotter(df, verbose = TRUE)

Here is a solution.
When splitting the data, split by year and state in the same instruction. Then loop through the split list plotting each data set. Save with ggave.

In the function below the output filenames depend on the combination year/state and I have included an argument verbose that prints the filenames as they are written to disk.

library(ggplot2)

boxplotter <- function(X, file = "boxplotter%s.pdf", width = 7, height = 5, verbose = FALSE){
  # create a list of data.frame's by year and state
  year_list <- split(X, list(X[["year"]], X[["state"]]), sep = "_")
  # remove from the list the empty sub-lists. This is needed
  # because there might be combinations of year/state not
  # present in the input data and 'split' will create them 
  # anyway
  year_list <- year_list[sapply(year_list, nrow) > 0L]
  
  # loop with an index into the list to make it possible
  # to get the data and also the names attribute, used
  # to form the output filenames
  for(i in seq_along(year_list)){
    # work with a copy, this just makes the code that
    # follows easier to read
    Y <- year_list[[i]]
    # plot and save the plot
    filename <- sprintf(file, names(year_list)[i])
    g <- ggplot(Y, aes(x=dept, y=corp_tax)) + 
      geom_boxplot(outlier.colour="red", outlier.shape=8,outlier.size=4) +
      scale_y_continuous(limits=c(0, max(Y$corp_tax, na.rm=TRUE)))
    ggsave(filename, plot = g, device = "pdf", width = width, height = height)
    # want to see what was written to disk?
    if(verbose){
      msg <- paste("output file:", filename)
      message(msg)
    }
  }
  # return nothing
  invisible(NULL)
}

boxplotter(df, verbose = TRUE)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文