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

R ggplot绘制同图例上下排布双柱状图及stat_count报错处理

问题原因

geom_bar()默认使用stat = "count"统计逻辑,仅用于统计单变量的出现频次,因此只能接受x或y中的一个美学映射。你当前已经明确传入了x(日期)和y(利润率)两个变量,需要直接使用现有数值作为柱高,和默认统计逻辑冲突,因此触发报错。

修改后可运行代码

library(ggplot2)

plot <- ggplot(d1_6b, aes(x = datadate, y = pr_margin, fill = conm)) + 
  geom_bar(stat = "identity") +
  facet_wrap(~conm, nrow = 2) + # 指定nrow=2实现上下排布
  theme_minimal() +
  ylab('Profit Margin') +
  xlab('Fiscal Year')

plot

如果需要两个子图的y轴范围独立适配各自的数据,可以给facet_wrap增加scales = "free_y"参数:

facet_wrap(~conm, nrow = 2, scales = "free_y")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:06:04