【问题标题】:Matplotlib force figure size of output imageMatplotlib 强制输出图像的图形大小
【发布时间】:2020-06-11 12:18:24
【问题描述】:

我正在创建一个 matplotlib 图。而且我希望输出图像的大小(或至少纵横比)保持一致。 似乎使用 figsize 会更改包含的图形,但不会更改图像。

fig, ax = plt.subplots(figsize=(9,9))
ax.barh([0,1,2],[1,5,3])
ax.set_yticks([0,1,2])
ax.set_yticklabels(['a','b','c'])

创建以下内容:

虽然ticklabels 的更改会放大图像

fig, ax = plt.subplots(figsize=(9,9))
ax.barh([0,1,2],[1,5,3])
ax.set_yticks([0,1,2])
ax.set_yticklabels(['a really really really really really really long name','b','c'])

我希望相反 - 保持输出大小相同并根据需要更改图表。

【问题讨论】:

  • 您可以尝试添加以下内容:fig.canvas.layout.width = '9in'fig.canvas.layout.height= '9in' 看看是否有效
  • AttributeError: 'FigureCanvasAgg' object has no attribute 'layout'
  • 我只使用 fig.canvas.width = '9in' fig.canvas.height = '9in' 删除了 layout 但它不起作用

标签: python matplotlib charts


【解决方案1】:

我能够设计出以下解决方案。尽管我不认为它是最好的解决方案,但它确实起到了一定的作用。思路如下:

  1. 获取 y-ticklabels 的宽度英寸(我使用了this 方法)
  2. 提取最大宽度,即最长刻度标签
  3. 使用 width = 9-max(label width) 在末尾重置图形大小

# Rest of your code

fig.canvas.draw()

# Get the labels' widths in inches
label_widths = [item.get_window_extent().transformed(fig.dpi_scale_trans.inverted()).width 
                for item in ax.get_yticklabels()]

Since the original size was 9 inches by 9 inches, rescale the size
fig.set_size_inches((9-max(label_widths)), 9)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 2016-10-12
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多