Create Plotly plot for each column in df with a 'for' loop

Viewed 1494

I want to make multiple Plotly Scatter plots (one for each column) in a df using a for loop in Python. I also want to be able to show the plots by entering the column name.

See sample code:

import plotly.express as px
import pandas as pd

df = pd.DataFrame({'A': [3, 1, 2, 3],
                   'B': [5, 6, 7, 8],
                   'C': [2, 1, 6, 3]})
df

     A    B    C
0    3    5    2
1    1    6    1
2    2    7    6
3    3    8    3

The closest I got is this:

for i in df.columns:
i = px.scatter(df,
               x="A",
               y=i)

But this fails to assign a value to each plot. I want to be able to show the plot for column A by entering A, and the plot for B by entering B, etc.

1 Answers

You can add the plots to a dict like

plots = {i: px.scatter(df, x="A", y=i) for i in df.columns}

which is equivalent but shorter than

plots = {}
for i in df.columns:
    plots[i] = px.scatter(df, x="A", y=i)

and then you can show each plot with plots['A'], plots['B'] and plots['C']

Related