Matplotlib线条重叠/分辨率
我在用Matplotlib画图,想让不同的线在x值不一样的时候不要重叠。但是奇怪的是,当这些线靠得很近(但不重叠)的时候,它们还是会重叠。例如,
fig = plt.figure(num=None, facecolor='w', edgecolor='k')
ax = fig.add_subplot(2, 1, 1)
ax.plot((0, 10000000), (3, 3), linewidth = 2, markersize = 0, clip_on = True, aa = True)
ax.plot((10000001, 200000001), (3, 3), linewidth = 1, markersize = 0, clip_on = True, aa = True)
plt.savefig('test.png', format='png')
我希望蓝线和绿线完全不重叠,因为10000000小于10000001。
我把蓝线画得稍微粗一点,所以如果你放大,就能看到蓝线和绿线是重叠的。我把dpi设置得很高,所以这不是分辨率的问题。我需要处理大数字,因为我在研究基因组数据——这些大数字会有问题吗?当我用x值在(0到10000)
和(10001, 20000)
的时候,这个问题依然存在。
非常感谢你的帮助。
1 个回答
4
这和Line2D
对象的线条端点样式有关,默认的样式是“投影”,这会导致线条重叠,看看放大的PDF:

我们想把它改成“平头”样式:
L1=ax.plot((0, 10000000), (3, 3), linewidth = 2, markersize = 0, clip_on = True, aa = True)
L2=ax.plot((10000001, 200000001), (3, 3), linewidth = 1, markersize = 0, clip_on = True, aa = True)
for item in L1+L2:
item.set_solid_capstyle('butt')
这个间隙非常小,确实是1/10000000。
或者,如果你想要一个快速简单的解决办法,可以在(10000000.5, 3)
的位置画一个大小为1的小白色圆点。
matplotlib.pyplot.plot
可以使用来自matplotlib.lines.Line2D
的kwargs
,其中包括参数solid_capstyle
- 这里有一个额外的例子,展示如何在绘图时设置
solid_capstyle
fig, ax = plt.subplots(1, 1, figsize=(8, 4))
L1 = ax.plot((0, 1), (1, 1), linewidth=10, label='No capstyle')
L2 = ax.plot((1, 2), (1, 1), linewidth=7, label='No capstyle')
L3 = ax.plot((0, 1), (0.9, 0.9), linewidth=10, solid_capstyle='butt', label='With butt capstyle')
L4 = ax.plot((1, 2), (0.9, 0.9), linewidth=7, solid_capstyle='butt', label='With butt capstyle')
ax.set_ylim(0, 2)
ax.grid()
ax.legend()