我有一个数据框,我可以绘制三种不同的图(条形图、堆积条形图和线图),但我只需要使用子图绘制一个图形。可以吗?
我的代码:
import pandas as pd
import plotly.express as px
data = pd.DataFrame([['A',0.25,0.25,0.25,0.25,125,0.032],
['B',0.20,0.40,0.15,0.25,175,0.054],
['C',0.25,0.25,0.30,0.20,192,0.065]])
data.columns = ['GROUP','Q1','Q2','Q3','Q4','SALES','IND']
data = data.set_index('GROUP')
data
fig1 = px.bar(data['SALES'], text_auto=True)
fig1.show()
fig2 = px.bar(data[['Q1','Q2','Q3','Q4']])
fig2.show()
fig3 = px.line(data['IND'])
fig3.show()type here
我只能添加两个图(条形图和线条图),但无法添加堆叠条形图
我试过这个:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=2, cols=1)
df1 = pd.DataFrame(data['SALES'])
df1.reset_index(inplace=True)
fig.add_trace(go.Bar(x=df1['GROUP'],y=df1['SALES']),1,1)
df2 = pd.DataFrame(data['IND'])
df2.reset_index(inplace=True)
fig.add_trace(go.Scatter(x=df2['GROUP'],y=df2['IND']),2,1)
fig.show()
由于 x 轴是分类变量,因此条形图和堆叠条形图重叠。避免这种情况的第三种方法是数据框并将堆叠图的 x 轴更改为
[0,1,2]
和 [0.5,1.5,2.5]
以避免重叠。同时,第二个 y 轴用于读取值。最后,将第一个图的 x 轴刻度更改为两个图之间中点处的值和变量名称。可能有比我的方法更简单的方法。
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=2, cols=1, specs=[[{"secondary_y": True}],[{"secondary_y": False}]])
df1 = pd.DataFrame(data['SALES'])
df1.reset_index(inplace=True)
fig.add_trace(go.Bar(x=[0,1,2], y=df1['SALES'], width=0.48, name='SALES'),1,1)#df1['GROUP']
df3 = pd.DataFrame(data[['Q1','Q2','Q3','Q4']])
df3.reset_index(inplace=True)
fig.add_trace(go.Bar(x=[0.5,1.5,2.5], y=df3['Q1'], width=0.480, name='Q1'),1,1,secondary_y=True)#df3['GROUP']
fig.add_trace(go.Bar(x=[0.5,1.5,2.5], y=df3['Q2'], width=0.480, name='Q2'),1,1,secondary_y=True)
fig.add_trace(go.Bar(x=[0.5,1.5,2.5], y=df3['Q3'], width=0.480, name='Q3'),1,1,secondary_y=True)
fig.add_trace(go.Bar(x=[0.5,1.5,2.5], y=df3['Q4'], width=0.480, name='Q4'),1,1,secondary_y=True)
fig.update_layout(barmode='stack')
fig.update_xaxes(tickvals=[0.25,1.25,2.25], ticktext=['A','B','C'], row=1, col=1)
df2 = pd.DataFrame(data['IND'])
df2.reset_index(inplace=True)
fig.add_trace(go.Scatter(x=df2['GROUP'],y=df2['IND'], name='IND'),2,1)
fig.show()