此代码使我能够绘制“3d”数组 [X,Y,Z] 的颜色图(它们是 3 个简单的 np.array 元素)。但是我无法在颜色条图例的右侧添加一个垂直的书写标签。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure("Color MAP 2D+")
contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")
#Legend
def fmt(x, pos):
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
return r'${} \times 10^{{{}}}$'.format(a, b)
import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
plt.show()
无法从 google 得到简单的答案,这很烦人...有人可以帮助我吗?
最佳答案
您要向 colorbar
对象添加一个 label
。值得庆幸的是,colorbar
有一个 set_label
功能。
简而言之:
cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')
在一个最小的脚本中:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
X = np.random.uniform(-2, 2, 200)
Y = np.random.uniform(-2, 2, 200)
Z = X*np.exp(-X**2 - Y**2)
contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")
def fmt(x, pos):
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
return r'${} \times 10^{{{}}}$'.format(a, b)
cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')
plt.show()
关于python - 向 matplotlib 颜色图图例添加垂直标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637989/