如何在Python Plotly中绘制带有多个Y轴的分组条形图

4

我需要绘制一个带有两个y轴和一个x轴的分组条形图。 如果在matplotlib中绘制,图表如下所示

enter image description here

我希望用Python的Plotly来实现,但是我找不到解决方案。似乎两年前有一个类似的问题(链接),但当我尝试按照相似的方式操作时,它并没有起作用。
这是我测试过的代码片段:
import plotly
import plotly.graph_objs as go
import numpy as np
import pandas as pd
from io import StringIO

s = StringIO("""     amount     price
A     40929   4066443
B     93904   9611272
C    188349  19360005
D    248438  24335536
E    205622  18888604
F    140173  12580900
G     76243   6751731
H     36859   3418329
I     29304   2758928
J     39768   3201269
K     30350   2867059""")

df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True)

plotly.offline.plot({
    "data": [go.Bar(x=df.index, y=df.price, name="price"),
             go.Bar(x=df.index, y=df.amount, name="amount", yaxis='y2'),
             ],
    "layout": go.Layout(title="Amount and price", 
                        yaxis=dict(
                            title='price',
                            autorange = True,
                            range = [0, max(df.price)],
                        ),
                        yaxis2=dict(
                            title='amount',
                            autorange = True,
                            range = [0, max(df.amount)],
                                overlaying='y',
                                side='right'                                
                        ),           
                        barmode='group',
                        autosize=True),
})

请注意,我已经设置了barmode='group',但这没有生效。

这篇链接的帖子似乎是最好的解决方案。 - vestland
1个回答

0

使用secondary_y:

df.plot.bar(secondary_y=['price'])

输出:

enter image description here


谢谢回复。但我想使用Plotly而不是matplotlib来完成它。 - Royalblue

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接