能否用Plotly或ggplot绘制共享X轴的双纵轴堆叠柱状图?
共享X轴双纵轴堆叠柱状图实现方案(Plotly + ggplot2)
完全可以用Plotly或ggplot2实现你需要的目标图表,以下是具体实现思路和代码示例:
Plotly 实现方式
Plotly的子图功能可直接支持双纵轴+堆叠柱状的组合,核心是通过make_subplots配置双纵轴,再给同纵轴的系列设置stackgroup参数实现堆叠:
import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd # 模拟示例数据 df = pd.DataFrame({ 'X轴类别': ['A', 'B', 'C', 'D'], '系列1-左轴': [10, 15, 12, 8], '系列2-左轴': [5, 7, 6, 4], '系列3-右轴': [200, 250, 180, 220], '系列4-右轴': [100, 130, 90, 110] }) # 创建双纵轴子图 fig = make_subplots(specs=[[{"secondary_y": True}]]) # 添加左轴堆叠柱状 fig.add_trace( go.Bar(x=df['X轴类别'], y=df['系列1-左轴'], name='系列1', stackgroup='left'), secondary_y=False ) fig.add_trace( go.Bar(x=df['X轴类别'], y=df['系列2-左轴'], name='系列2', stackgroup='left'), secondary_y=False ) # 添加右轴堆叠柱状 fig.add_trace( go.Bar(x=df['X轴类别'], y=df['系列3-右轴'], name='系列3', stackgroup='right'), secondary_y=True ) fig.add_trace( go.Bar(x=df['X轴类别'], y=df['系列4-右轴'], name='系列4', stackgroup='right'), secondary_y=True ) # 配置轴标签和布局 fig.update_layout( title='共享X轴双纵轴堆叠柱状图', xaxis_title='X轴类别', yaxis_title='左轴数值', yaxis2_title='右轴数值' ) fig.show()
关键细节:用stackgroup给同纵轴的系列分组,secondary_y指定轴归属,X轴会自动共享。
ggplot2 实现方式
ggplot2通过sec_axis支持双纵轴,结合position_stack()可实现堆叠柱状,需注意副轴的数值缩放(适配主轴范围):
library(ggplot2) library(tidyr) # 模拟示例数据 df <- data.frame( X轴类别 = c('A', 'B', 'C', 'D'), 系列1_左轴 = c(10, 15, 12, 8), 系列2_左轴 = c(5, 7, 6, 4), 系列3_右轴 = c(200, 250, 180, 220), 系列4_右轴 = c(100, 130, 90, 110) ) # 整理左轴系列为长格式 df_left <- df %>% select(X轴类别, 系列1_左轴, 系列2_左轴) %>% pivot_longer(cols = -X轴类别, names_to = '左轴系列', values_to = '数值') # 整理右轴系列为长格式,同时转换数值适配左轴范围 df_right <- df %>% select(X轴类别, 系列3_右轴, 系列4_右轴) %>% pivot_longer(cols = -X轴类别, names_to = '右轴系列', values_to = '数值') %>% mutate(转换后数值 = 数值 / 20) # 缩放比例根据实际数据调整 # 绘制图表 ggplot() + # 左轴堆叠柱状 geom_col(data = df_left, aes(x = X轴类别, y = 数值, fill = 左轴系列), position = position_stack()) + # 右轴堆叠柱状 geom_col(data = df_right, aes(x = X轴类别, y = 转换后数值, fill = 右轴系列), position = position_stack(), alpha = 0.7) + # 设置双纵轴 scale_y_continuous( name = '左轴数值', sec.axis = sec_axis(~ . * 20, name = '右轴数值') # 反向转换回原数值 ) + labs(x = 'X轴类别', title = '共享X轴双纵轴堆叠柱状图') + theme_minimal()
关键细节:副轴基于主轴数值转换,需手动计算缩放比例;通过两次geom_col分别绘制左右轴的堆叠系列,自动共享X轴。
内容的提问来源于stack exchange,提问作者biouser
相关产品推荐
相关产品推荐

