Matplotlib:在一幅图中创建多个子图 [英] Matplotlib: create multiple subplot in one figure
本文介绍了Matplotlib:在一幅图中创建多个子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据列,其列为x1, x2, x3, x4, x5, x6, my_y
.我正在为每个xi〜y绘制散点图,例如:
I have a data frame has columns x1, x2, x3, x4, x5, x6, my_y
. I am making a scatter plot for each xi ~ y like:
%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])
我对x1, x2, x3, x4, x5, x6
重复了上述代码6次,以创建6个图形.我想知道是否可以用6个散点图制作一个图形?谢谢!
I repeated the above code 6 times for x1, x2, x3, x4, x5, x6
, to create 6 figures. I am wondering if it possible to make one figure with 6 scatter subplots? Thanks!
推荐答案
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
方法.
Option1
Use the scatter
method from the axes
elements.
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()
这篇关于Matplotlib:在一幅图中创建多个子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文