[英]cant plot seaborn graphs side by side
我在这里做过研究,我发现的所有答案都不能解决我的问题。 我有 4 个直方图,我想要 plot 超过 2 行和 2 列。
如果我只想在 1 行上使用 plot 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)`
我可以请引导到正确的方向吗?
看看这个:这里我首先定义我想使用 plt.subplots(nrows, ncols) 制作多少个子图。 我也设置了sharex=True,这意味着你将共享x轴。 如果您想为所有 4 个子图设置单独的 x 轴,则将其设为 sharex=False (默认)
这里我使用随机生成的数据生成plot,大家可以使用自己的数据。
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")
对于具有m
行和n
列的子图图形,其中m
> 1 和n
> 1, plt.subplots()
返回形状为m
x n
的二维Axes
数组。 这样做是为了更容易使用行/列索引访问特定轴:
fig, axes = plt.subplots(nrows=2, ncols=2)
bottom_right_ax = axes[1, 1]
由于它是Axes
的二维数组,因此您需要稍微不同的解包语法才能使您的代码工作:
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
在上面的行中,元组(ax1, ax2)
解包到 2D Axes
数组的第一(顶)行,元组(ax3, ax4)
对最后(底)行执行相同操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.