0

How can we create mutiple boxplot at once using matplotlib or seaborn? For example, in a data frame I have numerical variable 'y' and 4 catergorical variables. So, I want 4 box plot for each of the categorial variable with 'y' at once. I can do one by one which is the forth line of the code for one categorical variable. I am attaching my code.

# Create boxplot and add palette
# with predefined values like Paired, Set1, etc
#x=merged_df[["MinWarrantyInMonths","MaxWarrantyInMonths"]]
sns.boxplot(x='MinWarrantyInMonths', y="CountSevereAlarm",
            data=merged_df, palette="Set1")


import matplotlib.pyplot as plt
plt.style.use('ggplot')
from ggplot import ggplot, aes, geom_boxplot

import pandas as pd
import numpy as np

data = merged_df
#labels = np.repeat(['A','B'],20)
merged_df[["MinWarrantyInMonths","MaxWarrantyInMonths"]]=labels
data.columns = ['vals','labels']

ggplot(data, aes(x='vals', y='labels')) + geom_boxplot()
ash1
  • 393
  • 1
  • 2
  • 10

1 Answers1

1

I hope I understood correctly what you're asking. If so, I suggest you try a for loop + using plt.subplot to create them together (side by side for example). See this:

columns = ['col1', 'col2', 'col3', 'col4']

for n, column in enumerate(columns):
    ax = plt.subplot(1, 4, n + 1)
    sns.boxplot(x=column, y="CountSevereAlarm", data=merged_df, palette="Set1")

within the plt.subplot you'll need to specify the number of rows and columns you want. In your situation this is 1 row, 4 columns (because you're interested in 4 box plots). The n+1 means the index location. Alternatively, (4,1,n+1) means that you'll have 4 rows, 1 column and box plots will appear one after another (not side by side).

I hope this helps. You can also read online about Matplotlib and subplots as there are other options to get the same result as you want.