How to get matplotlib to place lines accurately?
<p>By default, matplotlib plot can place lines very inaccurately.</p>

<p>For example, see the placement of the left endpoint in the attached plot. There's at least a whole pixel of air that shouldn't be there. In fact I think the line center is 2 pixels off.</p>

<p>How to get matplotlib to draw <strong>accurately</strong>? I don't mind if there is some performance hit.</p>

<p>Inaccurately rendered line in matplotlib plot:</p>

<p><a href="http://i.stack.imgur.com/siGbJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/siGbJ.png" alt="inaccurately rendered line in matplotlib plot"></a></p>

<p>Inaccurately rendered line in matplotlib plot - detail magnified:</p>

<p><a href="http://i.stack.imgur.com/luXjK.png" rel="nofollow"><img src="http://i.stack.imgur.com/luXjK.png" alt="inaccurately rendered line in matplotlib plot - detail magnified"></a></p>

<p>This was made with the default installations in Ubuntu 16.04 (Python 3), Jupyter notebook (similar result from command line).</p>

<p>Mathematica, for comparison, does subpixel-perfect rendering directly and by default:
<a href="http://i.stack.imgur.com/E4oB6.png" rel="nofollow"><img src="http://i.stack.imgur.com/E4oB6.png" alt="Same thing rendered by Mathematica"></a>
Why can't we?</p>

<p>Consider the following to see what is going on</p>

<pre><code>import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 4], clip_on=False, lw=5, alpha=.5)
ax.set_xlim([1, 3])

fig.savefig('so.png', dpi=400)
</code></pre>

<p><a href="http://i.stack.imgur.com/1s56E.png" rel="nofollow"><img src="http://i.stack.imgur.com/1s56E.png" alt="example"></a></p>

<p>You can also disable pixel snapping by passing <code>snap=False</code> to <code>plot</code>, however once you get down to placing ~ single pixel wide line, you are going to have issues because the underlying rasterization is too coarse.</p>

python matplotlib