You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写R函数:生成带第三列筛选条件的指定列Top10条形图

R函数:生成筛选后指定列的Top10条形图

以下是满足需求的函数实现,包含数据筛选、Top10提取和绘图逻辑:

# 定义核心函数
plot_top10 <- function(df, target_col, filter_col, filter_value, sort_col) {
  # 1. 筛选符合条件的数据,同时排除排序列的NA值
  filtered_data <- df[df[[filter_col]] == filter_value & !is.na(df[[sort_col]]), ]
  
  # 2. 按指定列降序排序,取前10条(如果数据不足10条则取全部)
  top10_data <- filtered_data[order(-filtered_data[[sort_col]]), ][1:min(10, nrow(filtered_data)), ]
  
  # 3. 绘制条形图(这里用ggplot2示例,可替换为你熟悉的绘图方式)
  ggplot2::ggplot(top10_data, ggplot2::aes(x = reorder(.data[[target_col]], .data[[sort_col]]), y = .data[[sort_col]])) +
    ggplot2::geom_bar(stat = "identity", fill = "#2c3e50") +
    ggplot2::coord_flip() +
    ggplot2::labs(title = paste("Top10", target_col, "按", sort_col, "排序(筛选条件:", filter_col, "=", filter_value, ")"),
                  x = target_col, y = sort_col) +
    ggplot2::theme_minimal()
}

参数说明

  • df: 输入的数据集
  • target_col: 需要在条形图上展示的列名(比如示例中的coaster_Data.name)
  • filter_col: 用于筛选的列名(比如示例中的coaster_Data.material_type)
  • filter_value: 筛选列的目标取值(比如示例中的"Wooden")
  • sort_col: 确定Top10排序依据的列名(比如示例中的coaster_Data.speed)

示例调用

用你提供的测试数据运行函数:

# 加载示例数据
subset_coaster <- structure(list(coaster_Data.name = c("Goudurix", "Dream catcher", 
"Alucinakis", "Anaconda", "Azteka", "Bat Coaster", "Batman : Arkham Asylum", 
"Big Thunder Mountain", "EqWalizer", "Calamity Mine", "Casey Jr, le Petit Train du Cirque", 
"Cobra", "Coccinelle", "Coleoz'Arbres", "Comet", "Course de Bobsleigh", 
"Cumbres", "Le Dragon de Bei Hai", "Euro Mir", "Eurosat", "Expedition Ge Force", 
"Le Grand canyon", "Indiana Jones et le Temple du Péril", "Jaguar", 
"Cop Car Chase (1)", "Loup Garou", "Magnus Colossus", "Oki Doki", 
"SOS Numerobis", "Poseïdon"), coaster_Data.material_type = structure(c(1L, 
1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L), levels = c("Steel", 
"Wooden", "Hybrid", "na"), class = "factor"), coaster_Data.speed = c(75, 
45, 30, 85, 55, 70, 80, 60, 76, 48, 30, 76, 36, 60, 64, 65, NA, 
NA, 80, 60, 120, 50, 58, 83, 60, 80, 92, 58, 32, 70)), row.names = c(NA, 
30L), class = "data.frame")

# 调用函数生成图表
plot_top10(df = subset_coaster,
           target_col = "coaster_Data.name",
           filter_col = "coaster_Data.material_type",
           filter_value = "Wooden",
           sort_col = "coaster_Data.speed")

注意事项

  • 若筛选后的数据不足10条,函数会自动取全部有效数据
  • 代码中使用.data[[col]]语法,避免ggplot2的非标准求值警告
  • 如果你习惯使用基础绘图包,可将ggplot部分替换为barplot()相关代码

内容的提问来源于stack exchange,提问作者Uzair Pawaskar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:15:29