[英]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.