从pandas pivot选项卡生成绘图热图

2024-09-28 22:33:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我搜索这个主题已经有几个小时了,但仍然无法使我的代码正常工作。我正在尝试从我用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')

这可能是一个相当简单的任务,我只是在编码方面没有学到太多东西,非常感谢您能提供的任何帮助。在


Tags: go类型编码dfdatafigrgbcountry
1条回答
网友
1楼 · 发布于 2024-09-28 22:33:21

显然,Plotly并不直接支持数据帧。但您可以将数据帧转换为如下列表的字典:

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

然后像Plotly这样的非Pandas工具应该可以工作,因为dict和list在默认情况下是JSON序列化的。在

相关问题 更多 >