Add a vertical label to matplotlib colormap legend

送分小仙女□ 提交于 2020-07-20 11:38:06

问题


This code enables me to plot a colormap of a "3d" array [X,Y,Z] (they are 3 simple np.array of elements). But I can't succeed in adding a vertical written label at the right of the colorbar legend.

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()

It's anoying to not get an easy answer from google... can someone help me ?


回答1:


You are looking to add a label to the colorbar object. Thankfully, colorbar has a set_label function.

in short:

cbar = plt.colorbar(contour, format=ticker.FuncFormatter(fmt))
cbar.set_label('your label here')

In a minimal script:

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()




回答2:


I believe your code is working. See this example:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris().data
X = iris[:,0]
Y = iris[:,1]
Z = iris[:,2]

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()

Output:



来源:https://stackoverflow.com/questions/47637989/add-a-vertical-label-to-matplotlib-colormap-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!