为什么我不能使用 fig.show() 来绘制我的图形



我还是不太懂剧情。我从kaggle得到这个代码。

import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot, plot
trace1 =go.Scatter(
x = df2015['Country'],
y = df2015['Happiness Score'],
mode = "markers",
name = "2015",
marker = dict(color = 'red'),
#line = dict(color='firebrick', width=4, dash='dot'),
text= df2015.Country)
trace2 =go.Scatter(
x = df2015['Country'],
y = df2016['Happiness Score'],
mode = "markers",
name = "2016",
marker = dict(color = 'green'),
text= df2016.Country)
trace3 =go.Scatter(
x = df2015['Country'],
y = df2017['Happiness Score'],
mode = "markers",
name = "2017",
marker = dict(color = 'blue'),
text= df2017.Country)
trace4 =go.Scatter(
x = df2015['Country'],
y = df2018['Happiness Score'],
mode = "markers",
name = "2018",
marker = dict(color = 'black'),
text= df2017.Country)
trace5 =go.Scatter(
x = df2015['Country'],
y = df2019['Happiness Score'],
mode = "markers",
name = "2019",
marker = dict(color = 'pink'),
text= df2017.Country)
data = [trace1, trace2, trace3, trace4, trace5]
layout = dict(title = 'Happiness Rate Changing 2015 to 2019 for Top 20 Countries',
xaxis= dict(title= 'Country',ticklen= 5,zeroline= False),
yaxis= dict(title= 'Happiness',ticklen= 5,zeroline= False),
hovermode="x"
)
fig = dict(data = data, layout = layout)
iplot(fig)

这个使用iplot来显示图形。但是当我尝试用fig.show()替换iplot(如https://plotly.com/python/line-and-scatter/#connected-scatterplots中建议的)时,我得到了这个错误:

AttributeError: 'dict' object has no attribute 'show'

有人知道为什么会这样吗?

您得到这个错误是因为您创建了dict,而不是plotly Figure。

替换fig = dict(data = data, layout = layout)

fig = go.Figure(data = data, layout = layout)

fig.show()

,它应该工作。

最新更新