Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib axhline: linewidth changes X position of line

I’ve observed some weird effects of using linewidth param in axhline from matplotlib.pyplot. I want to make line bolder, but this param makes line wider too.

For example, linewidth = 1:
enter image description here

and linewidth = 25:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

X position of these blocks makes really big difference for me. I can’t accept errors as big as that. Do you have any ideas how to make this line bolder without changing their X position?

>Solution :

If the lines you are drawing are limited between a minimum and a maximum value, then you should use matplotlib.pyplot.hlines in place of matplotlib.pyplot.axhline. Moreover you can control the line endings style with capstyle parameter:

import matplotlib.pyplot as plt


fig, ax = plt.subplots()

ax.hlines(y = 1, xmin = 1, xmax = 2, color = 'red', linewidth = 1, label = 'linewidth = 1, default capstyle')
ax.hlines(y = 2, xmin = 1, xmax = 2, color = 'green', linewidth = 25, capstyle = 'projecting', label = 'linewidth = 25, "projecting" capstyle')
ax.hlines(y = 3, xmin = 1, xmax = 2, color = 'blue', linewidth = 25, capstyle = 'butt', label = 'linewidth = 25, "butt" capstyle')

ax.set_xlim(-1, 4)
ax.set_ylim(-1, 5)

ax.legend(frameon = True)

plt.show()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading