【问题标题】:Pandas - Plotly subplots with grouped chartsPandas - 用分组图表绘制子图
【发布时间】:2020-11-03 21:20:45
【问题描述】:

我有以下两个相似的数据框,其中包含两个不同团队的数据

数据帧A:

name         bat_pos_1 ing_1_runs bat_pos_2 ing_2_runs
jack           2           10            2         20
john           1           20            1         5

数据帧B:

name         bat_pos_1 ing_1_runs bat_pos_2 ing_2_runs
jill           5           20            3         30
nancy          4            5            2         7

我正在使用下面的代码来呈现一个 poltly 分组的条形图

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

figTeamARuns = go.Figure(data=[
    go.Bar(name='Ist Inning', x=dataFrameA['name'], y=dataFrameA['ing_1_runs']),
    go.Bar(name='2nd Inning', x=dataFrameA['name'], y=dataFrameA['ing_2_runs']),
   ])
figTeamARuns.update_layout(barmode='group')
figTeamARuns.show()

figTeamBRuns = go.Figure(data=[
    go.Bar(name='Ist Inning', x=dataFrameB['name'], y=dataFrameB['ing_1_runs']),
    go.Bar(name='2nd Inning', x=dataFrameB['name'], y=dataFrameB['ing_2_runs']),
   ])
figTeamBRuns.update_layout(barmode='group')
figTeamBRuns.show()

上面的代码呈现了两个图表,一个在另一个之下,但我希望相同的图表并排显示。我知道我可以使用情节子图来完成,但我不知道该怎么做。这是我正在尝试使用的代码

figFinalBatting = go.Figure()
figFinalBatting = make_subplots(rows=1, cols=2)

我不知道下一步该做什么。有什么想法吗?

【问题讨论】:

    标签: dataframe plotly bar-chart subplot


    【解决方案1】:

    我认为docs 在这里很清楚。定义 fig 后,您需要添加每个跟踪并在行中指定您希望它出现的子图方案的 col。

    import pandas as pd
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    fig = make_subplots(rows=1, cols=2)
    fig.add_trace(
        go.Bar(name='Ist Inning',
               x=dataFrameA['name'],
               y=dataFrameA['ing_1_runs']),
        row=1, col=1)
    
    fig.add_trace(
        go.Bar(name='2nd Inning',
               x=dataFrameA['name'],
               y=dataFrameA['ing_2_runs']),
        row=1, col=1)
    
    fig.add_trace(
        go.Bar(name='Ist Inning',
               x=dataFrameB['name'],
               y=dataFrameB['ing_1_runs']),
        row=1, col=2)
    
    fig.add_trace(
        go.Bar(name='2st Inning',
               x=dataFrameB['name'],
               y=dataFrameB['ing_2_runs']),
        row=1, col=2)
    
    fig.show()
    

    【讨论】:

    • 完美运行,谢谢!我试图找到,但其他答案显示将数据数组传递给子图但没有用。没有意识到只为不同的轨迹提及同一列会导致对条形进行分组。
    • 你就在这里。在文档中没有这种例子。
    • 在这里您可以考虑添加一个图例组,甚至更好地连接 2 个数据框。
    猜你喜欢
    • 2015-09-25
    • 2015-08-03
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2017-01-27
    • 2015-04-02
    相关资源
    最近更新 更多