Matplotlib: add_lines to colorbar with defined properties (color: OK; dotted: not OK)

matplotlib

Solution

You could plot a horizontal line on your color bar directly.

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

You'll have to calculate the y-coordinate of the line based on the data and the coloramp.

Problem

I want to place a line at one level (e.g., 0) in the `colorbar` of a `contourf` plot with `matplotlib`. With the following code, I can do it but not all the properties of the `contour` lines are conserved (i.e., the color and width of the line are correct, but I can't have it dotted in the colorbar). Any idea of how to have a dotted line corresponding to a desired level in the colorbar? ``` 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() ```

Original source