【问题标题】:Generating a Plotly Heat Map from a pandas pivot table从 pandas 数据透视表生成 Plotly 热图
【发布时间】:2018-09-24 09:49:57
【问题描述】:

我已经搜索这个主题几个小时了,但仍然无法让我的代码工作。我正在尝试从使用 pandas 创建的数据透视表生成热图。我对编码很陌生,可能没有使用正确的术语,但我会尽力而为。

我的桌子是这样的:

enter image description here

它还有更多的行。我正在尝试用 y 轴上的国家、x 上的 4 种所有权类型以及用作 z 值的数值生成一个绘图热图。我遇到了很多错误,但我想我已经接近了,因为它到达了我的最后一行并说“TypeError:'DataFrame' 类型的对象不是 JSON 可序列化的。”我已经搜索了这个错误,但找不到任何我能理解的东西。我这样设置表格,但在 z、x 和 y 输入方面遇到问题:

data = [go.Heatmap(z=[Country_Ownership_df[['Company Owned', 'Franchise', 'Joint Venture', 'Licensed']]],
                   y=[Country_Ownership_df['Country']],
                   x=['Company Owned', 'Franchise', 'Joint Venture', 'Licensed'],
                   colorscale=[[0.0, 'white'], [0.000001, 'rgb(191, 0, 0)'], [.001, 'rgb(209, 95, 2)'], [.005, 'rgb(244, 131, 67)'], [.015, 'rgb(253,174,97)'], [.03, 'rgb(249, 214, 137)'], [.05, 'rgb(224,243,248)'], [0.1, 'rgb(116,173,209)'], [0.3, 'rgb(69,117,180)'], [1, 'rgb(49,54,149)']])]

layout = go.Layout(
    margin = dict(t=30,r=260,b=30,l=260),
    title='Ownership',
    xaxis = dict(ticks=''),
    yaxis = dict(ticks='', nticks=0 )
)
fig = go.Figure(data=data, layout=layout)
#iplot(fig)
plotly.offline.plot(fig, filename= 'tempfig3.html')

这可能是一项相当简单的任务,我只是没有学到太多的编码知识,感谢您提供的任何帮助。

【问题讨论】:

    标签: python pandas dictionary plotly heat


    【解决方案1】:

    显然 Plotly 不直接支持 DataFrames。但是你可以把你的 DataFrames 变成这样的列表字典:

    Country_Ownership_df[['foo', 'bar']].to_dict()
    

    那么像 Plotly 这样的非 Pandas 工具应该可以工作,因为字典和列表默认是 JSON 可序列化的。

    【讨论】:

      【解决方案2】:

      Plotly 将数据参数作为列表,不支持 Pandas DataFrames。要获取格式正确的 DataFrame,

      1. 数据作为值(Plotly 表示法中的“z”),
      2. x 值作为列
      3. y 值作为索引

      以下功能起作用:

      def df_to_plotly(df):
          return {'z': df.values.tolist(),
                  'x': df.columns.tolist(),
                  'y': df.index.tolist()}
      

      由于它返回一个dict,您可以直接将它作为参数传递给go.HeatMap

      import plotly.graph_objects as go
      
      fig = go.Figure(data=go.Heatmap(df_to_plotly(df)))
      fig.show()
      

      【讨论】:

      • 我做了什么:'z': mydf["counts"], 'x': mydf["something"], 'y': mydf["other"] inside df_to_plotly。跨度>
      • 这帮助了我一个区别,z 轴不需要.tolist()
      猜你喜欢
      • 2017-09-01
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 2015-09-27
      • 1970-01-01
      • 2014-04-27
      • 2021-01-17
      相关资源
      最近更新 更多