【发布时间】:2014-01-28 05:32:24
【问题描述】:
我想用我从数据框传递到下面函数的值来注释热图。我查看了 matplotlib.text 但无法在我的热图中以所需的方式从我的数据框中获取值。我在下面粘贴了用于生成热图的函数,之后是我的数据框和热图调用的输出。我想在热图中每个单元格的中心绘制我的数据框中的每个值。
生成热图的函数:
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def heatmap_binary(df,
edgecolors='w',
#cmap=mpl.cm.RdYlGn,
log=False):
width = len(df.columns)/7*10
height = len(df.index)/7*10
fig, ax = plt.subplots(figsize=(20,10))#(figsize=(width,height))
cmap, norm = mcolors.from_levels_and_colors([0, 0.05, 1],['Teal', 'MidnightBlue'] ) # ['MidnightBlue', Teal]['Darkgreen', 'Darkred']
heatmap = ax.pcolor(df ,
edgecolors=edgecolors, # put white lines between squares in heatmap
cmap=cmap,
norm=norm)
ax.autoscale(tight=True) # get rid of whitespace in margins of heatmap
ax.set_aspect('equal') # ensure heatmap cells are square
ax.xaxis.set_ticks_position('top') # put column labels at the top
ax.tick_params(bottom='off', top='off', left='off', right='off') # turn off ticks
plt.yticks(np.arange(len(df.index)) + 0.5, df.index, size=20)
plt.xticks(np.arange(len(df.columns)) + 0.5, df.columns, rotation=90, size= 15)
# ugliness from http://matplotlib.org/users/tight_layout_guide.html
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", "3%", pad="1%")
plt.colorbar(heatmap, cax=cax)
plt.show()
这是我的数据框的一个例子:
dataframe :
0-5 km / h 5-40 km / h 40-80 km / h 80-120 km / h \
NORDIC 0.113955 0.191888 0.017485 -0.277528
MIDDLE EU 0.117903 0.197084 -0.001447 -0.332677
KOREA 0.314008 0.236503 -0.067174 -0.396518
CHINA 0.314008 0.236503 -0.067174 -0.396518
120-160 km / h 160-190 km / h 190 km / h
NORDIC -0.054365 0.006107 0.002458
MIDDLE EU 0.002441 0.012097 0.004599
KOREA -0.087191 0.000331 0.000040
CHINA -0.087191 0.000331 0.000040
生成热图:
heatmap_binary(dataframe)
有什么想法吗?
更新以澄清我的问题
我尝试了问题中提出的解决方案,该解决方案具有我正在寻找的结果: how to annotate heatmap with text in matplotlib? 但是,使用 matplotlib.text 函数在热图中定位值仍然存在问题: 这是我尝试此解决方案的代码:
import matplotlib.pyplot as plt
import numpy as np
data = dataframe.values
heatmap_binary(dataframe)
for y in range(data.shape[0]):
for x in range(data.shape[1]):
plt.text(data[y,x] +0.05 , data[y,x] + 0.05, '%.4f' % data[y, x], #data[y,x] +0.05 , data[y,x] + 0.05
horizontalalignment='center',
verticalalignment='center',
color='w')
#plt.colorbar(heatmap)
plt.show()
添加情节:(不同的颜色,但同样的问题)
【问题讨论】:
-
尝试这个时出了什么问题?可以发张图片吗?
-
添加了一张图片,不同的颜色但同样的问题。文本调用将值放在右上角....
-
你能一次性发布你的代码副本,而不是分成两个不同的块吗?我认为问题在于您在添加
colorbar之后 运行for循环。尝试在调用pcolor之后立即运行textfor循环。 -
我试图在 pcolor 之后将 for 循环放在 heatmap_binary 函数旁边...但没有工作...我得到了相同的结果
标签: python text matplotlib pandas heatmap