python - 向 matplotlib 颜色图图例添加垂直标签

标签 python matplotlib label colormap

此代码使我能够绘制“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()

enter image description here

无法从 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()

enter image description here

关于python - 向 matplotlib 颜色图图例添加垂直标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637989/

相关文章:

python 用逗号分割字符串而不是在矩阵表达式内

python - 两个数据帧的硬匹配,无需迭代

python - 将文本添加到python中的图例

python - 如何使用 matplotlib 绘制类似 gnuplot 的 'with impulses' 的样式?

python - seaborn:默认情况下绝望图

user-interface - "undefined reference to ` gtk_label_set_xalign '"编译 Vala 应用程序时

来自 django.contrib.auth.views 的 Python 导入注销 ImportError : cannot import name 'logout'

python - Airflow 中的 op_kwargs 和 templates_dict od PythonOperator 有什么区别?

ruby-on-rails - 在循环运行时无法使用 ruby​​ on Rails 中的标签选择单选按钮?

forms - Symfony2 - 在表单中编辑标签显示名称