python - 如何将条形图的 x + y 轴与绘图上给定的数据帧列相关联

标签 python plotly

我有一个小数据框,想从中导出条形图。条形图将有 2 个 y 轴输入,每个 x 轴值。我使用了 plotly 文档来尽可能地继续,但不知何故我无法将列与输入相关联。

这是我的数据框:

    Club            FTHG    FTAG
0   Augsburg        24      19
1   Bayern Munich   56      36
2   Dortmund        40      24
3   Ein Frankfurt   26      19
4   FC Koln         20      15

代码:

data = [go.Bar(
                x=Club.index, y=FTHG.values, name = 'Goals'
        )]

layout = go.Layout(title = 'Goals')


trace0 = go.Bar(
    x=[Club.index],
    y=[FTHG.index],
    name='Home Goals',
    marker=dict(
        color='rgb(49,130,189)'
    )
)
trace1 = go.Bar(
    x=[Club.index],
    y=[FTAG.index],
    name='Away Goals',
    marker=dict(
        color='rgb(204,204,204)',
    )
)

data = [trace0, trace1]
layout = go.Layout(
    xaxis=dict(tickangle=-45),
    barmode='group',
)

fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='angled-text-bar')

错误:

> NameError                                 Traceback (most recent call
> last) <ipython-input-38-2dcf55a0f165> in <module>
>       1 data = [go.Bar(
> ----> 2                 x=Club.index, y=FTHG.values, name = 'Goals'
>       3         )]
>       4 
>       5 layout = go.Layout(title = 'Goals')
> 
> NameError: name 'Club' is not defined

有什么建议吗?

谢谢!

最佳答案

更改您的xy。如果您有 pandas DataFrame 并且想要分配列 - 使用 df["Club"] 或 df.Club。您可以分配 df.index - 在这种情况下,他将是一个列表,例如 [0,1,2,3,4]。

代码:

from plotly.offline import plot
import plotly.graph_objs as go
import pandas as pd

df = pd.DataFrame({"Club": ["Augsburg", "Bayern Munich", "Dortmund",
                            "Ein Frankfurt", "FC Koln"],
                   "FTHG": [24, 56, 40, 26, 20],
                   "FTAG": [19, 36, 24, 19, 15]})

trace0 = go.Bar(
    x=df["Club"],
    y=df["FTHG"],
    name='Home Goals',
    marker=dict(
        color='rgb(49,130,189)'
    )
)
trace1 = go.Bar(
    x=df["Club"],
    y=df["FTAG"],
    name='Away Goals',
    marker=dict(
        color='rgb(204,204,204)',
    )
)

data = [trace0, trace1]
layout = go.Layout(
    xaxis=dict(tickangle=-45),
    barmode='group',
)

fig = go.Figure(data=data, layout=layout)
plot(fig, filename='angled-text-bar')

你会得到一个不错的 plotly :

Stacked Bar Chart

关于python - 如何将条形图的 x + y 轴与绘图上给定的数据帧列相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54735577/

相关文章:

python - 正则表达式,过滤带数字和不带数字结尾的 url

javascript - 绘图设置颜色

r - 找不到对象 "new_panel"ggplotly 错误

python - Plotly:如何检查基本图形结构(版本 4)

python - Plotly 中的 nbins 是什么

python - 如果一列大于另一列则删除行

python - 如何使用 Python Tkinter 实现这种类型的结果?

python - 在两个 DAG 之间设置上游

Python 包未导入 AWS EMR 中

python - 如何在 python/plotly 中制作 2D 向量分布的 3D 直方图