NRVA
NRVA

Reputation: 507

Plotly: How to make multiple plots with colors based on a condition?

I want to make multiple Plotly Scatter plots (one for each column) in a df using a for loop in Python, which I get to work as expected.

Then I want the color of the plots to be conditional of the last value in the dataframe. Eg. if the last row is above or below 5, so in the example I want the plot for column B to have a differrent color than A and C.

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

making plots with Plotly and for loop:

plots = {}

for i in df.columns:
    if df.iloc[-1] >= 5:
        plots[i] = px.scatter(df, color_discrete_sequence=["red"], x="A", y=i)
    else:
        plots[i] = px.scatter(df, color_discrete_sequence=["blue"], x="A", y=i)

Here I expect to be able to show each plot with plots['A'], plots['B'] and plots['C'], but I expect plot A and C to be blue, and plot B to be red.

Upvotes: 1

Views: 1369

Answers (1)

vestland
vestland

Reputation: 61104

Structurally, your approach seems to be fine. But there are a few details that may cause some problems. df.iloc[-1] >= 5 can quickly raise an error, so I'd use dfx.iloc[-1].values >= 5 instead. Your dataframe subsetting isn't working either. And when you're subsetting a dataframe column by column, you often get a pandas series rather than a pandas dataframe. And their attributes are not the same. Taking these details intor consideration, I've put together the code below that produces the following plot by calling, for example, plots[2].show():

Plot 1

enter image description here

Give it a try an let me know how it works out for you.

Complete 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]})

plots = {}

for i, col in enumerate(df.columns):
    dfx = df[col].to_frame()
    print(dfx)
    if dfx.iloc[-1].values >= 5:
        plots[i] = px.scatter(df, color_discrete_sequence=["red"], x=df[col].index, y=df[col])
    else:
        plots[i] = px.scatter(df, color_discrete_sequence=["blue"], x=df[col].index, y=df[col])

plots[2].show()

Upvotes: 1

Related Questions