Group-by using pandas and plot lines in Plotly

Question:

I have the following df, and I am trying to build 2 different plots using Plotly.

df = pd.DataFrame({'weight':[12,11,10,14,16,13,12,15,16],
                   'height':[110,111,116,111,110,113,115,114, 112],
                   'name':['Adam', 'Steve','Mike', 'Adam', 'Adam', 'Steve', 'Mike','Mike','Steve'],
                   'category':[1,1,2,2,1,2,1,1,1]})

The first plot I am trying to build is to groupby the df by ‘name’ and plot weight versus height for each name. (see PLOT 1)
The second plot I want to build is to first groupby ‘Category’ then plot weight vs height for each ‘name’ as a subplot. If there are two categories (as in this example) then I want to have two subplots, if 3 categories then 3 subplots, and so on. (See PLOT 2)

enter image description here

Asked By: serdar_bay

||

Answers:

This can be done with a single call to px.line:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'weight':[12,11,10,14,16,13,12,15,16],
                   'height':[110,111,116,111,110,113,115,114, 112],
                   'name':['Adam', 'Steve','Mike', 'Adam', 'Adam', 'Steve', 'Mike','Mike','Steve'],
                   'category':[1,1,2,2,1,2,1,1,1]})

fig = px.line(df, x="weight", y="height", color='name', markers=True, facet_col="category")
fig.show()

Output:
enter image description here

You can specify how many columns will fit in a row with facet_col_wrap=n_col (see doc)

Answered By: Tranbi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.