【问题标题】:Matplotlib align uneven number of subplotsMatplotlib 对齐奇数个子图
【发布时间】:2021-09-07 11:55:03
【问题描述】:

我想使用子图绘制 11 个图形。我的想法是有 2 行:第一行 6 个地块,第二个地块 5 个。我使用以下代码。

import matplotlib.pyplot as plt
import pandas as pd

fig, axes = plt.subplots(2, 6, figsize=(30, 8))
fig.tight_layout(h_pad=6, w_pad=6)

x = 0
y = 0

for i in range(0, 11):
    data = [[1, i*1], [2, i*2*2], [3, i*3*3]]

    df = pd.DataFrame(data, columns = ['x', 'y'])
    
    df.plot('x', ['y'], ax=axes[x,y])
    
    y += 1
    if y > 5:
        y = 0
        x += 1

fig.delaxes(ax=axes[1,5])

这可行,但底行未与中心对齐,这使得结果有点难看。我希望所有数字都具有相同的大小,因此我无法扩展最后一个以使所有内容均等。

我的问题:如何使第二行居中对齐以使整张图片对称?

【问题讨论】:

  • 我个人喜欢使用fig = plt.figure(),然后是ax = plt.axes(left, bottom, width, height)...这样您就可以完美地自定义您想要的任何轴...matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axes.html
  • 第一行6块的宽度画第二行5块是不是错了?最简单的方法是使用 gridspec。

标签: python dataframe matplotlib


【解决方案1】:

您可以使用gridspec 将每一行分成 12 个分区并成对重新组合它们:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import pandas as pd

fig = plt.figure(figsize=(12, 5))
gs = gridspec.GridSpec(2, 12)

for i in range(0, 11):
    if i < 6:
        ax = plt.subplot(gs[0, 2 * i:2 * i + 2])
    else:
        ax = plt.subplot(gs[1, 2 * i - 11:2 * i + 2 - 11])
    data = [[1, i * 1], [2, i * 2 * 2], [3, i * 3 * 3]]
    df = pd.DataFrame(data, columns=['x', 'y'])

    df.plot('x', 'y', ax=ax)

plt.tight_layout()
plt.show()

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 2017-10-05
    • 2017-02-26
    • 2015-04-28
    • 2020-12-19
    • 1970-01-01
    • 2014-09-10
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多