Search code examples
pythonmatplotlibplotline

Matplotlib line width based on axis, not on points


If you set a line width in Matplotlib, you have to give the line width in points. In my case, I have two circles, both with radius R and I want to connect them with a line. I want this line to be 2*R wide in order to get a rod-shape. But when I say myLines[i].set_linewidth(2*R) this makes the lines always a specific thickness, regardless of how much I have zoomed in.

Is there a way to make lines a specific thickness not based on the number of pixels or points, but scaling with the axis? How can I make my line have the same width as the diameter of my circles?

I hope I explained myself well enough and I am looking forward to an answer.


Solution

  • Line in Data units

    In order to draw a line with the linewidth in data units, you may want to have a look at this answer.

    It uses a class data_linewidth_plot which closely resembles the plt.plot() command's signature.

    l = data_linewidth_plot( x, y, ax=ax, label='some line', linewidth = 1, alpha = 0.4)
    

    The linewidth argument is interpreted in (y-)data units.

    Using this solution there is not even any need for drawing circles, since one may simply use the solid_capstyle="round" argument.

    R=0.5
    l = data_linewidth_plot( [0,3], [0.7,1.4], ax=ax, solid_capstyle="round", 
                            linewidth = 2*R, alpha = 0.4)
    

    enter image description here

    Rod shape

    A rod is much more easily produced using a rectange and two circles. enter image description here