【问题标题】:Why can't I use fig.show() to plot my graph为什么我不能使用 fig.show() 来绘制我的图表
【发布时间】:2021-11-19 10:27:20
【问题描述】:

我仍然不太了解情节。我从 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'

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

【问题讨论】:

  • 我运行了你的代码来寻找类似的数据。没有产生错误并且图表显示正确。我的运行版本是 5.2.2。你用的是什么版本?

标签: plotly data-visualization


【解决方案1】:

您收到此错误是因为您创建了 dict,而不是 plotly Figure。

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

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

fig.show()

它应该可以工作。

【讨论】:

    猜你喜欢
    • 2016-07-12
    • 2015-09-20
    • 2013-07-21
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多