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

使用ggplot()绘制多层堆叠条形图的技术求助

Hey there! Let's work through this bar plot hurdle together. I notice your code cuts off at the mutate(pro... part—let's fill that in and build out the full ggplot2 implementation to get your bar charts working properly.

First, let's clean up and complete your existing code, then add the ggplot2 plotting logic:

Completed Code with ggplot2 Implementation

# 读取数据
parameter_results <- readRDS("param_results_2014.RDS")
# 参数名称列表
parameters <- sort(readRDS("parameters.RDS"))

bar_plot <- function(parameter) {
  parameter_df <- parameter_results %>% 
    select(results = parameter) %>%  # 重命名目标列,统一后续处理逻辑
    filter(results != "Not Applicable") %>%  # 剔除无效的"Not Applicable"条目
    count(results) %>%  # 统计每个结果出现的频数
    mutate(prop = n / sum(n))  # 计算每个结果的占比(推测这是你未写完的部分)
  
  # 用ggplot2绘制条形图
  ggplot(parameter_df, aes(x = results, y = n)) +
    geom_bar(stat = "identity", fill = "#2c3e50") +  # 绘制基础频数条形图
    # 添加带占比的数值标签,放在条形上方
    geom_text(aes(label = paste0(n, " (", round(prop*100, 1), "%)")), 
              vjust = -0.5, size = 3.5) +
    # 设置图表标题和坐标轴标签
    labs(title = paste("Distribution of", parameter),
         x = "Result Category",
         y = "Number of Occurrences") +
    # 使用简洁的主题,并调整x轴标签避免重叠
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 45, hjust = 1))
}

# 调用函数绘制第一个参数的条形图(可替换成parameters中的任意元素)
bar_plot(parameters[1])

Key Notes & Optimizations:

  • Completed the mutate step: I added prop = n / sum(n) to calculate the proportion of each result, which I assume was what you were working on when the code cut off.
  • Label clarity: The geom_text layer adds both the raw count and percentage to each bar, making the chart easier to interpret.
  • X-axis readability: Rotating x-axis labels by 45 degrees prevents overlap if your result categories have long names.
  • Sorting bars: If you want bars sorted by frequency (highest to lowest), add these lines right after count(results):
    arrange(desc(n)) %>% 
    mutate(results = forcats::fct_inorder(results))
    
    This uses the forcats package (part of the tidyverse) to reorder the factor levels by their frequency.
  • Proportion instead of count: If you want to plot proportions instead of raw counts, just change y = n to y = prop in the aes() call, and adjust the label to paste0(round(prop*100, 1), "%").

Let me know if you run into specific issues (like error messages, unexpected plot output) and we can tweak this further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:52:19