Change capstyle for errorbars in matplotlib

2019-05-22 20:28发布

问题:

I would like to set the capstyle for the vertical lines of an error bar to 'round'. For example, the following code produces some points with errorbars:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plt.plot([1,2,3], [2,3,4], marker='o', linestyle='None')
plt.errorbar([1,2,3], [2,3,4], yerr=[1,1,1], fmt=None, linewidth=3, capsize=0)
plt.xlim([0,4])
plt.show()

For normal lines, I can set the cap style in the rcParams using this:

plt.rcParams['lines.dash_capstyle'] = 'round'

and I also found some nice examples how to get round capstyles for ticks:

for i in ax.xaxis.get_ticklines(): i._marker._capstyle = 'round'

but I am not able to find a similar way for the errorbars.

回答1:

plotline, cap, barlinecols =\
         plt.errorbar([1,2,3], [2,3,4], yerr=[1,1,1], fmt=None, linewidth=3, capsize=0)

plt.errorbar returns 3 objects. plotline and cap are Line2D objects, which you can then do:

plotline.set_capstyle('round')
cap.set_capstyle('round')

barlinecols is a LineCollection object. However, the current version (matplotlib 2.0) does not support changing capstyle in LineCollection objects (see: https://github.com/matplotlib/matplotlib/issues/8277). But it looks like this will be implemented in the next version.



回答2:

To give a working code here to change the capstyle of the vertical errorbar lines:

import matplotlib.pyplot as plt

plotline, caps, barlinecols =\
         plt.errorbar([1,2,3], [2,3,4], yerr=[1,1,1], linewidth=5, capsize=0)

plt.setp(barlinecols[0], capstyle="round", color="orange")

plt.show()

To instead change the capstyle of the errorbar caps, one would need to use some private attributes,

import matplotlib.pyplot as plt

plotline, caps, barlinecols =\
         plt.errorbar([1,2,3], [2,3,4], yerr=[1,1,1], linewidth=1, capsize=8, capthick=5)

for cap in caps:
    cap._marker._capstyle = "round"

plt.show()