简体   繁体   English

如何在python中绘制具有多个y轴的分组条形图

[英]How to plot grouped bar chart with multiple y axes in python plotly

I need to plot a grouped bar chart with two y axes and one x axis.我需要绘制一个带有两个 y 轴和一个 x 轴的分组条形图。 The plot looks like the following if drawn in matplotlib如果在 matplotlib 中绘制,该图如下所示

在此处输入图片说明

I want it by python plotly but I could not find a solution.我想通过python plotly,但我找不到解决方案。 There seems to be a similar question two years ago两年前好像有过类似的问题

https://stackoverflow.com/questions/29046057/plotly-grouped-bar-chart-with-multiple-axes https://stackoverflow.com/questions/29046057/plotly-grouped-bar-chart-with-multiple-axes

but did not work when I tried to do it similarly.但是当我尝试类似地做时没有用。

Here is the code snippet that I tested:这是我测试的代码片段:

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),
})

please note that I gave barmode='group' but this does not take effect.请注意,我给了 barmode='group' 但这不起作用。

Use secondary_y :使用secondary_y

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

Output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM