How to draw rounded line ends using matplotlib

atomh33ls picture atomh33ls · May 19, 2015 · Viewed 7.9k times · Source

Say I am plotting a complex value like this:

a=-0.49+1j*1.14
plt.polar([0,angle(x)],[0,abs(x)],linewidth=5)

Giving

enter image description here

Is there a setting I can use to get rounded line ends, like the red line in the following example (drawn in paint)?

enter image description here

Answer

tacaswell picture tacaswell · May 19, 2015

The line proprty solid_capstyle (docs). There is also a dash_capstyle which controls the line ends on every dash.

import matplotlib.pyplot as plt
import numpy as np

x = y = np.arange(5)

fig, ax = plt. subplots()

ln, = ax.plot(x, y, lw=10, solid_capstyle='round')
ln2, = ax.plot(x, 4-y, lw=10)
ln2.set_solid_capstyle('round')
ax.margins(.2)

enter image description here

This will work equally will with plt.polar, which is a convenience method for creating a polar axes and calling plot on it, and the the Line2D object returned by it.