I would like to plot positive and negative word charts for each category together on the same grid. To achieve that, I’m using plt.subplot()
. I’m using for loop to plot graphs for all the categories. My question is: how can I place two categories’ graphs (positive and negative charts for each category on the same grid) in 1 row?
for category in results_df['Category'].unique():
plt.figure(figsize=(6, 4))
plt.subplot(1, 2, 1)
subset_positive = results_df[(results_df['Category'] == category) & (results_df['Sentiment'] == 'Positive')]
subset_positive = subset_positive.sort_values(by='Frequency', ascending=False)
ax = sns.barplot(x='Frequency', y='Word', data=subset_positive, color=sns.color_palette('muted')[2])
ax.set(ylabel = '', xlabel='')
plt.title('Positive Words')
plt.subplot(1, 2, 2)
subset_negative = results_df[(results_df['Category'] == category) & (results_df['Sentiment'] == 'Negative')]
subset_negative = subset_negative.sort_values(by='Frequency', ascending=False)
ax = sns.barplot(x='Frequency', y='Word', data=subset_negative, color=sns.color_palette('muted')[0])
ax.set(ylabel = '', xlabel='')
plt.title('Negative Words')
plt.subplots_adjust(wspace=0.5, top = 0.85)
plt.suptitle(f'Most Frequent Words in Comments for {category}')
plt.show()
I tried the following code
categories = results_df['Category'].unique()
fig, axs = plt.subplots(7, 2, figsize=(20, 35))
axs = axs.flatten()
for i, category in enumerate(categories):
subset_positive = results_df[(results_df['Category'] == category) & (results_df['Sentiment'] == 'Positive')]
subset_positive = subset_positive.sort_values(by='Frequency', ascending=False)
ax = axs[i * 2]
sns.barplot(x='Frequency', y='Word', data=subset_positive, color=sns.color_palette('muted')[2], ax=ax)
ax.set_title(f'Positive Words - {category}')
subset_negative = results_df[(results_df['Category'] == category) & (results_df['Sentiment'] == 'Negative')]
subset_negative = subset_negative.sort_values(by='Frequency', ascending=False)
ax = axs[i * 2 + 1]
sns.barplot(x='Frequency', y='Word', data=subset_negative, color=sns.color_palette('muted')[0], ax=ax)
ax.set_title(f'Negative Words - {category}')
plt.tight_layout()
plt.show()
But this created all the separate charts on the same graph. Is it possible to keep the graphs separated but place them side by side (2 in one row)?