首页 > 解决方案 > an instance of :class:`plotly.graph_objs.Bar`

问题描述

Plotting Pandas in Plotly Subplots throwing this error

from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=1, cols=2)
fig.add_trace(go.Bar(worldData_2, x='TotalCases', y='Country', orientation='h'),row=1, col=1)
fig.add_trace(go.Bar(worldData_2, x='TotalDeaths', y='Country', orientation='h'),row=1, col=2)
fig.update_yaxes(categoryorder='total ascending')
fig.update_layout(height=600, width=800, title_text="COVID19", showlegend=False)
fig.show()

Error, Whats the error

2644 The first argument to the plotly.graph_objs.Bar
   2645 constructor must be a dict or
-> 2646 an instance of :class:`plotly.graph_objs.Bar`"""
   2647             )
   2648 

ValueError: The first argument to the plotly.graph_objs.Bar 
constructor must be a dict or 
an instance of :class:`plotly.graph_objs.Bar`

How to pass the Pandas DataFrame

标签: pandasplotly-python

解决方案


从 go.Bar 上的 plotly 文档中,一个位置参数是:

arg - 与此构造函数或 plotly.graph_objects.Bar 实例兼容的属性字典

这是错误消息的来源,因为 DataFrame 是意外的。

这与接受DataFrame作为参数的 px.Bar 不同:

data_frame (DataFrame or array-like or dict) – 需要传递这个参数才能使用列名(而不是关键字名)。Array-like 和 dict 在内部转换为 pandas DataFrame。可选:如果缺少,则使用其他参数在后台构建 DataFrame。


由于go.Bar只接受xandy参数的坐标集,因此将and传递Series给。xy

就像是:

fig = make_subplots(rows=1, cols=2)
fig.add_trace(
    go.Bar(x=worldData_2['TotalCases'], y=worldData_2['Country'],
           orientation='h'),
    row=1, col=1
)
fig.add_trace(
    go.Bar(x=worldData_2['TotalDeaths'], y=worldData_2['Country'],
           orientation='h'),
    row=1, col=2
)
fig.update_yaxes(categoryorder='total ascending')
fig.update_layout(height=600, width=800, title_text="COVID19", showlegend=False)
fig.show()

推荐阅读