python - TypeError: dtype 对象的图像数据无法转换为浮点数 - 使用 Seaborn 的 HeatMap Plot 问题
问题描述
我收到错误:
TypeError: Image data of dtype object cannot be converted to float
当我尝试heapmap
在下面的代码中运行该函数时:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Read the data
df = pd.read_csv("gapminder-FiveYearData.csv")
print(df.head(10))
# Create an array of n-dimensional array of life expectancy changes for countries over the years.
year = ((np.asarray(df['year'])).reshape(12,142))
country = ((np.asarray(df['country'])).reshape(12,142))
print(year)
print(country)
# Create a pivot table
result = df.pivot(index='year',columns='country',values='lifeExp')
print(result)
# Create an array to annotate the heatmap
labels = (np.asarray(["{1:.2f} \n {0}".format(year,value)
for year, value in zip(year.flatten(),
country.flatten())])
).reshape(12,142)
# Define the plot
fig, ax = plt.subplots(figsize=(15,9))
# Add title to the Heat map
title = "GapMinder Heat Map"
# Set the font size and the distance of the title from the plot
plt.title(title,fontsize=18)
ttl = ax.title
ttl.set_position([0.5,1.05])
# Hide ticks for X & Y axis
ax.set_xticks([])
ax.set_yticks([])
# Remove the axes
ax.axis('off')
# Use the heatmap function from the seaborn package
hmap = sns.heatmap(result,annot=labels,fmt="",cmap='RdYlGn',linewidths=0.30,ax=ax)
# Display the Heatmap
plt.imshow(hmap)
这是 CSV 文件的链接。
活动的目标是
data 文件是包含 6 列的数据集,即:国家、年份、流行、大陆
lifeExp
和gdpPercap
.创建一个数据透视表数据框,x 轴为年份,y 轴为国家,并
lifeExp
在单元格内填充。使用 seaborn 为刚刚创建的数据透视表绘制热图。
解决方案
感谢您为此问题提供数据。我相信您的 typeError 来自labels
您的代码为注释创建的数组。基于函数的内置注释属性,我实际上认为您不需要这些额外的工作,它会以一种在绘图时出错的方式修改您的数据。
我尝试重新编写您的项目以生成显示 和 的数据透视表的country
热year
图lifeExp
。我还假设保持这个数字对你很重要 a float
。
import numpy as np
import pandas as pd
import seaborn as sb
import matplotlib.pyplot as plt
## UNCHANGED FROM ABOVE **
# Read in the data
df = pd.read_csv('https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv')
df.head()
## ** UNCHANGED FROM ABOVE **
# Create an array of n-dimensional array of life expectancy changes for countries over the years.
year = ((np.asarray(df['year'])).reshape(12,142))
country = ((np.asarray(df['country'])).reshape(12,142))
print('show year\n', year)
print('\nshow country\n', country)
# Create a pivot table
result = df.pivot(index='country',columns='year',values='lifeExp')
# Note: This index and columns order is reversed from your code.
# This will put the year on the X axis of our heatmap
result
我删除了labels
代码块。功能注意事项sb.heatmap
:
- 我曾经
plt.cm.get_cmap()
限制映射中的颜色数量。如果您想使用整个颜色图谱,只需将其删除并包括您最初的方式。 fmt
= "f", this if forfloat
, 你的lifeExp
值。cbar_kws
- 您可以使用它来调整颜色条的大小、标签和方向。
# Define the plot - feel free to modify however you want
plt.figure(figsize = [20, 50])
# Set the font size and the distance of the title from the plot
title = 'GapMinder Heat Map'
plt.title(title,fontsize=24)
ax = sb.heatmap(result, annot = True, fmt='f', linewidths = .5,
cmap = plt.cm.get_cmap('RdYlGn', 7), cbar_kws={
'label': 'Life Expectancy', 'shrink': 0.5})
# This sets a label, size 20 to your color bar
ax.figure.axes[-1].yaxis.label.set_size(20)
plt.show()
推荐阅读
- python - MySQL 版本 8 Python 3.7 无法将 None 值写为 NULL
- sql - 如何将分层的图像文件夹与 CSV 文件集成?
- scala - 使用 rlike 和 list 创建新的 df scala
- python - Leetcode 28 问题 - 为什么我的 strStr() 失败了?
- string - 从字符串中提取信息 - ML 中的哪些技术可以解决
- mongodb - 批量写入时输入了错误的数据
- c - 反转C中的中缀表达式?
- spring - Dto 扩展 RepresentationalModel 总是在测试中返回“link:[]”
- python - SQLAlchemy 级联删除-孤儿不删除孤儿
- html - 使侧边栏从屏幕顶部下拉