【发布时间】:2020-05-19 13:48:56
【问题描述】:
我收到了错误:
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)
Here 是指向 CSV 文件的链接。
活动的目的是
数据文件是6列的数据集,分别为:国家、年份、流行、大陆、
lifeExp和gdpPercap。创建一个数据透视表数据框,x 轴为年份,y 轴为国家,
lifeExp填充在单元格内。使用 seaborn 为刚刚创建的数据透视表绘制热图。
【问题讨论】:
标签: python numpy matplotlib seaborn heatmap