Reputation: 906
I have done research here in SO and all the answers that i have found do not solve my issue. I have 4 histograms that i want to plot over 2 rows and 2 columns.
If i just want to plot 2 histograms over 1 row then it works fine but the moment i add more histograms then the whole thing dies! this is the code:
`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()`
and this is the error message that i get:
`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)`
can i please get steered in the right direction?
Upvotes: 1
Views: 4955
Reputation: 111
Check this out: Here I am first defining how many subplots I want to make using plt.subplots(nrows, ncols). Also I have put sharex=True, which means you will share x axis. If you want to have separate x axis for all 4 subplots then make it sharex=False (default)
Here I used randomly generated data to generate the plot, you can use your own data.
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")
Upvotes: 4
Reputation: 7509
For subplot figures with m
rows and n
columns, where m
> 1 and n
> 1, plt.subplots()
returns a 2D array of Axes
with shape m
x n
. This is done so that it's easier to acess a specific axis using row/column indices:
fig, axes = plt.subplots(nrows=2, ncols=2)
bottom_right_ax = axes[1, 1]
Since it's a 2D array of Axes
, you'll need a slightly different unpacking syntax for your code to work:
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
In the line above, the tuple (ax1, ax2)
unpacks to the first (top) row of the 2D Axes
array, and the tuple (ax3, ax4)
does the same for the last (bottom) row.
Upvotes: 1