显示热图中的词汇。Python

2024-06-28 15:07:33 发布

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

这是热图的代码。我想知道我是否可以把数字1,2,3,4改成字母,比如A,B,C,D,它们在每个正方形下面。你知道吗

'''
Most heatmap tutorials I found online use pyplot.pcolormesh with random sets of
data from Numpy; I just needed to plot x, y, z values stored in lists--without
all the Numpy mumbo jumbo. Here I have code to plot intensity on a 2D array, and
I only use Numpy where I need to (pcolormesh expects Numpy arrays as inputs).
'''
import matplotlib.pyplot as plt
import numpy as np

#here's our data to plot, all normal Python lists
x = [0, 1, 2, 3, 4,5]
y = [0, 1, 2, 3, 4,5]

intensity = [
    [5, 10, 15, 20, 25,3],
    [30, 35, 40, 45, 50,23],
    [55, 60, 65, 70, 75,34],
    [80, 85, 90, 95, 100,24],
    [105, 110, 115, 120, 125,23],
    [105, 110, 115, 120, 125,23]
]

#setup the 2D grid with Numpy
x, y = np.meshgrid(x, y)

#convert intensity (list of lists) to a numpy array for plotting
intensity = np.array(intensity)

#now just plug the data into pcolormesh, it's that easy!
plt.pcolormesh(x, y, intensity)
plt.colorbar() #need a colorbar to show the intensity scale
plt.show() #boom 

Tags: thetonumpydataplotuseaswith
2条回答

您将需要“设置标签”命令。设置强度后,我更改了您的代码,如下所示:

f, a = plt.subplots()
im = a.pcolormesh(x, y, intensity)
f.colorbar(im, ax = a) #need a colorbar to show the intensity scale
labels = [item.get_text() for item in a.get_xticklabels()]
labels = ['A', 'B', 'C', 'D', 'E', 'F']
a.set_xticklabels(labels) #set xtick
a.set_yticklabels(labels) #set ytick
plt.show() #boom 

如图所示:

a busy cat

最简单、最直接的方法是pyplot.xticks()方法,它专门针对x轴上的标签:

x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 2, 3, 4, 5]

# add these lines here    
x_ticks = ['', 'A', 'B', 'C', 'D', 'E']
plt.xticks(x, x_ticks)  

注意:第一个标签设置为空''以说明原点:

enter image description here

参考文献:http://matplotlib.org/2.0.2/api/pyplot_api.html#matplotlib.pyplot.xticks

相关问题 更多 >