I am new to Python and trying to plot multiple boxplots from a dataframe.
My dataframe is:
Date A B C D E
01-Jan 1 3 6 6 1
01-Feb 2 4 7 4 2
01-Mar 3 5 8 2 9
I want to create 5 boxplots with where each boxplot represents an individual letter. How can I do it within a graph? Is there a systematic way to do when I have 100 columns so I don't have to type the column names for 100 times?
CodePudding user response:
Or you can convert df
to dict
then plot boxplots
like below:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Date': ['01-Jan', '01-Feb', '01-Mar'],'A': [1,2,3],
'B': [3,4,5],'C': [6,7,8],'D': [6,4,2],'E': [1,2,9],})
df = df.drop('Date',1)
dct = df.to_dict('list')
labels = dct.keys()
plt.boxplot(dct.values())
plt.xticks(range(1, len(labels) 1), labels)
plt.show()
Output:
CodePudding user response:
Import the packages
import pandas as pd
import matplotlib.pyplot as plt
To create the boxplot (requires pandas)
df.boxplot(column=list(df.columns)) # All columns
df.boxplot(column=list(df[['B', 'D']].columns)) # Selected columns
df.boxplot(column=list(df.drop(['B', 'D'], axis=1).columns)) # Drop columns
To show the plot (requires matplotlib)
plt.show()
Link for more info
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.boxplot.html