如何格式化组合柱状图与折线图(含代码调整需求)
修改后的R代码(满足需求)
# 输入数据 year <- c("2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023") failures <- c(4, 11, 3, 4, 0, 0, 3, 25, 140, 157, 92, 51, 24, 18, 8, 5, 8, 0, 4, 4, 0, 0, 3) assets <- c(2358.6, 2705.4, 1045.2, 163.1, 0, 0, 2602.5, 373588.8, 170909.4, 96514, 36012.2, 12055.8, 6101.7, 3088.4, 6727.5, 278.8, 6530.7, 0, 214.1, 458, 0, 0, 548500) # 合并为数据框(原代码缺失此步骤) banks <- data.frame(year, failures, assets) # 加载所需包 library(ggplot2) library(scales) # 绘制组合图 ggplot(banks, aes(x = year)) + geom_col(aes(y = failures), size = 1, color = "dodgerblue4", fill = "white") + geom_line(aes(y = failures * (max(assets)/max(failures))), size = 1.5, color = "darkorange2", group = 1) + scale_y_continuous( name = "Number of Bank Failures", # 修改主Y轴标题 limits = c(0, max(failures) * 1.05), # 调整主Y轴缩放,确保柱状图清晰 sec.axis = sec_axis( ~ . / (max(assets)/max(failures)), # 匹配主副轴比例,优化可视化 name = "Total Assets ($M)", labels = dollar_format(prefix = "$", big.mark = ",") # 设置次Y轴数值格式为$100,000样式 ) ) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 可选:旋转X轴标签避免重叠
关键修改说明
- 补全数据框定义:原代码直接使用
banks但未创建,新增banks <- data.frame(year, failures, assets) - 主Y轴标题设置:通过
scale_y_continuous的name参数指定为要求的标题 - 次Y轴格式优化:借助
scales包的dollar_format()实现带美元符号和千分位的数值显示 - Y轴缩放调整:
- 主Y轴设置上下限为0到最大倒闭数的1.05倍,保证柱状图完整展示
- 用
max(assets)/max(failures)计算主副轴比例,让折线图与柱状图的缩放匹配,避免一方被压缩
内容的提问来源于stack exchange,提问作者Data and AI Nerd
相关产品推荐
相关产品推荐

