Matplotlib:add_lines到带有已定义属性的colorbar(颜色:OK;点缀:不行)

时间:2014-07-11 18:24:21

标签: matplotlib

我想在colorbar的{​​{1}}情节contourf中使用matplotlib在一个级别(例如0)放置一条线。 使用下面的代码,我可以做到,但不是contour行的所有属性都是守恒的(即,行的颜色和宽度是正确的,但我不能将它点缀在颜色栏中)。 想知道如何在颜色栏中找到与所需级别相对应的虚线吗?

import matplotlib.pyplot as plt
import numpy

x=y=range(10)
z=numpy.random.normal(0,2,size=(10,10))

surfplot=plt.contourf(x,y,z, cmap=plt.cm.binary_r)
cont=plt.contour(surfplot, levels=[0], colors='r', linewidths=5, linestyles=':')
cbar=plt.colorbar(surfplot)
cbar.add_lines(cont)

plt.show()

Levels in colorbar

2 个答案:

答案 0 :(得分:4)

您可以直接在颜色条上绘制水平线。

cax = cbar.ax
cax.hlines(0.5, 0, 1, colors = 'r', linewidth = 10, linestyles = ':')

dotted color bar line 您必须根据数据和coloramp计算线的y坐标。

答案 1 :(得分:1)

Colorbar.add_lines()当前为only retains the colors and line widths。 但是,您可以在添加新LineCollection的线条样式后对其进行更新:

import matplotlib.pyplot as plt
import numpy
plt.style.use('classic')  # to match the look in the question

x = y = range(10)
z = numpy.random.normal(0, 2, size=(10, 10))

surfplot = plt.contourf(x, y, z, cmap=plt.cm.binary_r)
cont = plt.contour(surfplot, levels=[0], colors='r', linewidths=5, linestyles=':')
cbar = plt.colorbar(surfplot)
cbar.add_lines(cont)
cbar.lines[-1].set_linestyles(cont.linestyles)  # adopt the contour's line styles

plt.show()

contour plot with dotted line also in color bar