【问题标题】:Matplotlib: create multiple subplot in one figureMatplotlib:在一个图中创建多个子图
【发布时间】:2017-08-03 19:31:25
【问题描述】:

我有一个数据框有列x1, x2, x3, x4, x5, x6, my_y。我正在为每个 xi ~ y 制作散点图,例如:

%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
my_df.plot(x='x1', y='my_y', kind = 'scatter', marker = 'x', color = 'black', ylim = [0, 10])

我对@9​​87654323@ 重复上述代码 6 次,以创建 6 个数字。我想知道是否可以用 6 个散点图制作一个图形?谢谢!

【问题讨论】:

  • 如果你这样做x=['x1', 'x2', 'x3', 'x4', 'x5', 'x6']会发生什么?

标签: python-3.x pandas matplotlib


【解决方案1】:
df = pd.DataFrame(
    np.random.randint(10, size=(5, 7)),
    columns='x1 x2 x3 x4 x5 x6 my_y'.split()
)

df

   x1  x2  x3  x4  x5  x6  my_y
0   0   8   3   2   7   5     8
1   0   6   2   5   8   4     9
2   4   7   1   2   6   4     5
3   8   5   4   0   5   7     4
4   5   6   0   1   8   7     2

选项1
使用来自axes 元素的scatter 方法。

fig, axes = plt.subplots(2, 3, figsize=(6, 4), sharex=True, sharey=True)
y = df.my_y.values
for i in range(6):
    axes[i//3, i%3].scatter(df.iloc[:, i].values, y)

fig.tight_layout()


选项 2
使用pandas.DataFrame.plot

fig, axes = plt.subplots(2, 3, figsize=(6, 4), sharex=True, sharey=True)
y = df.my_y.values
for i in range(6):
    df.plot(x='x' + str(i+1),
            y='my_y',
            kind='scatter',
            marker='x',
            color='black',
            ylim=[0, 10],
            ax=axes[i//3, i%3])

fig.tight_layout()


回复评论
没有sharex=True

fig, axes = plt.subplots(2, 3, figsize=(6, 4), sharey=True)
y = df.my_y.values
for i in range(6):
    df.plot(x='x' + str(i+1),
            y='my_y',
            kind='scatter',
            marker='x',
            color='black',
            ylim=[0, 10],
            ax=axes[i//3, i%3])

fig.tight_layout()

【讨论】:

  • 谢谢!还想知道在使用选项 2 时,是否可以为第一行子图设置 x 轴标签 (x1, x2, x3)?
  • 关闭我的sharex=True
猜你喜欢
  • 2020-02-11
  • 2015-10-20
  • 1970-01-01
  • 2015-10-24
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多