繁体   English   中英

使用rasterized = True时,Matplotlib绘图(pcolormesh和colorbar)相对于其轴移位

[英]Matplotlib plots (pcolormesh and colorbar) shift with respect to their axes when using rasterized=True

我使用pcolormesh matplotlib pcolormesh图,将光栅化应用于图和颜色条,以减小文件大小并将图形保存为PDF文件。 因此我注意到,在光栅化之后,颜色区域本身相对于轴向上和向左移动一点,从而在图的下边缘和右边缘出现白色条纹。 色条也是如此,我发现更糟糕的是:使用薄的彩条,白色条纹非常明显且令人不安。 有没有办法避免光栅化图的这种行为,并将光栅化区域保持在光栅化之前的相同位置?

我尝试使用rasterization_zorderzorder settings 它帮助一点与pcolormesh图(下部白色条纹消失了),但是我发现没有办法把它应用到的colorbar

下面有一个简单的例子,有四个图表证明了这个问题。 请放大图表右下边的PDF文件,看看我的意思。

    import numpy as np
    import matplotlib.pyplot as plt

    d = np.arange(100).reshape(10, 10)

    myfig = plt.figure(figsize=(5, 5)) 

    '''plot 1, no rasterization'''
    ax1 = plt.subplot(221)
    plot1 = ax1.pcolormesh(d)
    cbar1 = plt.colorbar(plot1)
    ax1.set_title("no rasterization", fontsize = 10)

    '''plot 2, main plot rasterized, colorbar not'''
    ax2 = plt.subplot(222)
    plot2 = ax2.pcolormesh(d, rasterized=True)
    cbar2 = plt.colorbar(plot2)
    ax2.set_title("plot rasterized", fontsize = 10)

    '''plot 3, main plot and colorbar rasterized'''
    ax3 = plt.subplot(223)
    plot3 = ax3.pcolormesh(d, rasterized=True)
    cbar3 = plt.colorbar(plot3)
    cbar3.solids.set_rasterized(True)  # !!!!!!!! 
    ax3.set_title("plot and cbar rasterized", fontsize = 10)

    '''plot 4, whole axes of main plot and colorbar rasterized, attempt to use rasterization_zorder'''
    ax4 = plt.subplot(224)
    ax4.set_rasterization_zorder(-10)
    plot4 = ax4.pcolormesh(d, zorder=-20)
    '''colorbarbar gets its own axis'''
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    ax_cbar4 = inset_axes(ax4,  width="3%", height="100%", loc=6)
    ax_cbar4.set_rasterization_zorder(-10)
    locator_ax_cbar4 =ax_cbar4.get_axes_locator()
    locator_ax_cbar4.set_bbox_to_anchor ((1.0, 0 , 1, 1),  ax4.transAxes)
    cbar4=plt.colorbar(plot4, cax=ax_cbar4)

    #cbar4.solids.set_rasterization_zorder(-10) # ---> NOT WORKING 
    cbar4.solids.set_rasterized(True)

    ax4.set_title("axes rasterized and zorder changed", fontsize = 10)


    plt.savefig("D:/test_rasterization_3plots.pdf", dpi=150)
    print 'pdf file saved'

    plt.show()

例

任何建议将不胜感激!

这是一个在1.2.0和1.2.1之间的某个地方修复的错误(也许这个: https//github.com/matplotlib/matplotlib/issues/1085 ,我留下追踪修复问题的提交作为练习为读者;))。

最简单的解决方案是升级到1.2.1或更高版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM