【问题标题】:Save a barplot in matplotlib without border, axes, whitespace在 matplotlib 中保存没有边框、轴、空白的条形图
【发布时间】:2018-03-20 14:21:41
【问题描述】:

使用matplotlib.pyplot,我想创建一个条形图,并将其保存到一个没有坐标轴、边框和额外空白的图像中。 Save spectrogram (only content, without axes or anything else) to a file using Matloptlib 的答案以及所有链接的问题和各自的答案似乎不适用于条形图。

到目前为止,我得到了:

import matplotlib.pyplot as plt

fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
fig.patch.set_facecolor('xkcd:mint green')
ax.set_facecolor('xkcd:salmon')
ax.axis('off')
ax.bar(1,1,1,-1,alpha=1, align='center', edgecolor='black')
ax.bar(2,1,1,-2,alpha=1, align='center', edgecolor='black')
ax.axis('off')
fig.savefig('test.png', dpi=300, frameon='false', pad_inches=0.0,bbox_inches='tight')

这三个问题:

  1. 左侧、顶部和右侧还有一些剩余的空白。
  2. 该图似乎在底部被切开,因为下部条的底线比其他条更细。
  3. 纵横比应该是 1:1,而且似乎是关闭的。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:
    1. 链接问题的答案不使用bbox_inches='tight'。这与没有空格的愿望相矛盾。 此外,当然还有一些边距inside 轴,因为条当然不直接位于轴边界。你可以设置ax.margins(0)
    2. 一条线延伸到坐标的两个方向,例如如果您在位置 0 处有一条宽度为 3 像素的线,您将在 0 上方获得一个像素,在 0 处获得一个像素,在 0 下方获得一个像素。如果您限制图像从位置 0 开始,则低于 0 的像素将被剪切。李>
    3. 纵横比没有理由应该是 1:1。但是如果你希望它是 1:1,你需要明确地设置它。 ax.set_aspect(1)。当然,这只有在图形也设置为具有相等的宽度和高度时才有意义。

    总计。

    import matplotlib.pyplot as plt
    
    fig,ax = plt.subplots(figsize=(5,5))
    fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
    fig.patch.set_facecolor('xkcd:mint green')
    ax.set_facecolor('xkcd:salmon')
    ax.axis('off')
    ax.margins(0)
    ax.set_aspect(1)
    ax.bar(1,1,1,-1,alpha=1, align='center', edgecolor='black')
    ax.bar(2,1,1,-2,alpha=1, align='center', edgecolor='black')
    
    fig.savefig('test.png', dpi=300, frameon=False, pad_inches=0.0)
    

    【讨论】:

    • 完美。也感谢您一贯的解释。
    猜你喜欢
    • 2018-09-21
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多