不能并排绘制seaborn图

时间:2019-10-30 11:44:35

标签: python matplotlib plot graph seaborn

我在这里做了SO方面的研究,发现的所有答案都不能解决我的问题。 我有4个直方图,想要绘制2行和2列。

如果我只想在1行上绘制2个直方图,则效果很好,但是当我添加更多直方图时,整个过程就会消失! 这是代码:

`fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=2, ncols=2)
sns.distplot(iot['opex_euro'],ax=ax1)
sns.distplot(iot['cost_of_delay'],ax=ax2)
sns.distplot(iot['customer_commitment_value'],ax=ax3)
sns.distplot(iot['ktlo_value'],ax=ax4)
plt.show()`

这是我收到的错误消息:

`ValueError Traceback (most recent call last)
<ipython-input-115-5b6d5d693b20> in <module>()
1 #plotParams()
2 
----> 3 fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=2, ncols=2)
4 sns.distplot(iot['opex_euro'],ax=ax1)
5 sns.distplot(iot['cost_of_delay'],ax=ax2)
ValueError: not enough values to unpack (expected 4, got 2)`

我能朝正确的方向转向吗?

2 个答案:

答案 0 :(得分:3)

检查一下:在这里,我首先使用plt.subplots(nrows,ncols)定义要创建多少个子图。另外,我将sharex = True放进去,这意味着您将共享x轴。如果要为所有4个子图使用单独的x轴,则将其设为sharex = False(默认)

在这里,我使用了随机生成的数据来生成图,您可以使用自己的数据。

import seaborn as sns
import matplotlib.pyplot as plt

f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)

sns.despine(left=True)

# Plot a simple distribution of the desired columns
sns.distplot(df['col1'], color="b", ax=axes[0, 0])
sns.distplot(df['col2'], color="m", ax=axes[0, 1])
sns.distplot(df['col3'], color="r", ax=axes[1, 0])
sns.distplot(df['col4'], color="g", ax=axes[1, 1])

plt.setp(axes, yticks=[])
plt.tight_layout()

plt.savefig("sample.png")

4 Subplots with shared x axis

答案 1 :(得分:1)

对于具有m行和n列的子图图形,其中m> 1和n> 1,plt.subplots()返回{{ 1}},形状为Axes x m。这样做是为了更轻松地使用行/列索引访问特定轴:

n

由于它是fig, axes = plt.subplots(nrows=2, ncols=2) bottom_right_ax = axes[1, 1] 的2D数组,因此您需要稍微不同的解压缩语法才能使代码正常工作:

Axes

在上面的行中,元组fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) 解压缩到2D (ax1, ax2)数组的第一行(顶部),而元组Axes对最后一个(底部)行相同行。