matplotlib中在不使用twiny()的情况下在热图的上方添加标签

46 阅读2分钟

在使用matplotlib绘制热图时,如果想在热图的上方添加标签,通常会使用twiny()函数。但是,使用twiny()可能会导致对齐问题,因此我们希望在不使用twiny()的情况下在热图的上方添加标签。

huake_00198_.jpg

2、解决方案

解决方案1:使用add_plot()函数在热图上添加额外的轴

import numpy as np
import matplotlib.pyplot as plt

x = "0.2, 0.3, 0.4, 0.5, 0.6".split(",")
y = "180, 175, 170, 169, 150".split(",")
z = [[5000, 4800, 4500, 4450, 4300]]

fig = plt.figure()
ax1 = fig.add_subplot(111)

image = z

im = ax1.imshow(image, cmap=plt.cm.Blues, interpolation='nearest')
plt.colorbar(im)

ax1.set_xticks(np.arange(len(x)), minor=False)
ax1.set_xticklabels(x, minor=False)
ax1.tick_params(labelbottom='on',labeltop='off', labelleft="off", 
    top='off', left='off', right='off')

# create another axes on the same position:
# - create second axes on top of the first one without background
# - make the background invisible
# - set the x scale according to that of `ax1`
# - set the top ticks on and everything else off
# - set the size according to the size of `ax1`
ax2 = fig.add_axes(ax1.get_position(), frameon=False)
ax2.tick_params(labelbottom='off',labeltop='on', labelleft="off", labelright='off',
    bottom='off', left='off', right='off')
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(np.arange(len(y)))
ax2.set_xticklabels(y, minor=False)

plt.draw()
ax2.set_position(ax1.get_position())

plt.draw()
plt.show()

解决方案2:使用text函数在热图上添加标签

import numpy as np
import matplotlib.pyplot as plt

x = "0.2, 0.3, 0.4, 0.5, 0.6".split(",")
y = "180, 175, 170, 169, 150".split(",")
z = [[5000, 4800, 4500, 4450, 4300]]

fig, ax1 = plt.subplots()

image = z

im = ax1.imshow(z, cmap=plt.cm.Blues, interpolation='nearest')
xticks = ax1.get_xticks()

top_lables_width_spacings = 0.83
top_lables_hight_spacings = -.53

for i in range(len(y)):
    ax1.text(xticks[i] + top_lables_width_spacings, top_lables_hight_spacings, y[i])

ax1.set_xticks(np.arange(len(x)), minor=False)
ax1.set_xticklabels(x, minor=False)

ax1.tick_params(labelbottom='on',labeltop='off', labelleft="off")

ax1.set_title('$\eta$\n', size=17)      # represents the top axes label
plt.xlabel(r'$\theta$', size=17)                        # represents the bottom axes label
plt.show()

解决方案3:使用twin()函数和mpl_toolkits.axes_grid1.host_subplot来在热图上添加标签

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import numpy as np

x = "0.2, 0.3, 0.4, 0.5, 0.6".split(",")
y = "180, 175, 170, 169, 150".split(",")
z = [[5000, 4800, 4500, 4450, 4300]]

ax1 = host_subplot(111, axes_class=AA.Axes)

ax2 = ax1.twin()
image = z

im = ax1.imshow(image, cmap=plt.cm.Blues, interpolation='nearest')
plt.colorbar(im)


ax1.set_xticks(np.arange(len(x)), minor=False)
ax2.set_xticks(np.arange(len(y)), minor=False)

ax1.set_yticklabels([])
ax2.set_yticklabels([])

ax1.tick_params(labelbottom='on',labeltop='on', labelleft="off")


plt.show()

以上三种解决方案都可以在不使用twiny()的情况下在热图的上方添加标签,具体使用哪种解决方案可以根据实际情况进行选择。