Carmen Moreno
Carmen Moreno

Reputation: 125

Creating multiple boxplots using plotly

I'm trying to replicate the following boxplot I made in matplotlib using plotly:


My data is in a very simple dataframe imported from an Excel file and looks like follows:

As you can see, I want to have the different conditions in the x-axis and a y-axis that covers from 0 to 10 and have a different box plot for each condition with its own mean, SD etc. However, when I try the following code I get a very weird output:

import plotly.express as px
conditions = df1.keys() #all conditions, df1 being my DataFrame
conditions=list(conditions)
fig = px.box(df1, x = conditions) 
fig.show()

Output:

Anyone knows what do I have to do to get a similar plot like the one I got with matplotlib but with plotly?

Upvotes: 5

Views: 13618

Answers (2)

ASH
ASH

Reputation: 20302

import plotly.express as px

df = px.data.tips()

fig = px.box(df, x="day", y="total_bill", color="smoker")
fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default
fig.show()

enter image description here

Upvotes: 1

M--
M--

Reputation: 28825

You can use plotly.express or plotly.graph_objects.

Reading data:

import pandas as pd

df = pd.read_csv(r'Documents\test.csv', sep=',')
print(df)
print(df.to_dict())
   p=0; t=0  p=1; t=6"  p=1; t=30"  p=3; t=6"  p=3; t=30"  p=3; t=1'
0         0          3           3          2          10         10
1         2          3           5          4           9          9
2         2          6           1          1          10          9
3         1          1           4          2           7          8

{'p=0; t=0': {0: 0, 1: 2, 2: 2, 3: 1}, 'p=1; t=6"': {0: 3, 1: 3, 2: 6, 3: 1}, 
 'p=1; t=30"': {0: 3, 1: 5, 2: 1, 3: 4}, 'p=3; t=6"': {0: 2, 1: 4, 2: 1, 3: 2}, 
 'p=3; t=30"': {0: 10, 1: 9, 2: 10, 3: 7}, "p=3; t=1'": {0: 10, 1: 9, 2: 9, 3: 8}}

plotly.graph_objects:

import plotly.graph_objects as go

fig = go.Figure()

for col in df:
  fig.add_trace(go.Box(y=df[col].values, name=df[col].name))
  
fig.show()

plotly.express:

import plotly.express as px

fig = px.box(pd.melt(df), x="variable", y="value", points="outliers")
fig.show()

Upvotes: 10

Related Questions