Plots: How to draw multiple plots with colors based on conditions?


NRVA

I want to make multiple Plotly Scatter plots (one per column) in df using a for loop in Python.

Then I want the color of the plot to depend on the last value in the dataframe. E.g. If the last row is above or below 5, then in the example I want the graph in column B to have a different 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

Plot with Plotly and a 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 want to be able to use plots['A'], plots''B'] and plots['C'] to display each plot, but I want plots A and C to be blue and plot B to be red.

Vest

Structurally, your approach seems fine. But some details may cause some problems. df.iloc[-1] >= 5Can throw an error quickly, so I'll use that dfx.iloc[-1].values >= 5instead. A subset of your dataframe doesn't work either. When you subset a dataframe column by column, you usually get a pandas series instead of a pandas dataframe. And their properties are not the same. With these details in mind, I've put together the following code to produce the following chart, for example, by calling the following code plots[2].show():

plot 1

enter image description here

Give it a try and let me know how it works 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()

Related


How to change the colors of multiple frequency plots?

Codedude I am plotting multiple frequency responses on the same curve using "hold" and "freqz" in MATLAB. Is there any way to adjust the colors of each plot so that I can determine which is which? It looks like a mess now. Freqz doesn't seem to support changin

How to change the colors of multiple frequency plots?

Codedude I am plotting multiple frequency responses on the same curve using "hold" and "freqz" in MATLAB. Is there any way to adjust the colors of each plot so that I can determine which is which? It looks like a mess now. Freqz doesn't seem to support changin

How to change the colors of multiple frequency plots?

Codedude I am plotting multiple frequency responses on the same curve using "hold" and "freqz" in MATLAB. Is there any way to adjust the colors of each plot so that I can determine which is which? It looks like a mess now. Freqz doesn't seem to support changin

How to change the colors of multiple frequency plots?

Codedude I am plotting multiple frequency responses on the same curve using "hold" and "freqz" in MATLAB. Is there any way to adjust the colors of each plot so that I can determine which is which? It looks like a mess now. Freqz doesn't seem to support changin

How to change the colors of multiple frequency plots?

Codedude I am plotting multiple frequency responses on the same curve using "hold" and "freqz" in MATLAB. Is there any way to adjust the colors of each plot so that I can determine which is which? It looks like a mess now. Freqz doesn't seem to support changin

How to draw multiple plots in a for loop with warnings?

Yelanbo The structure of my code (just an example) is basically this: xs <- c("a","b") for(x in xs) { png(filename = paste(x,".png",sep="") ggplot() dev.off() } When I just run the code alone inside the loop, it produces a png file perfectly, but in Rstudio i

How to draw multiple tiled plots in a single figure?

Tobias Wood I want to plot multiple swarmplots in one figure. I think swarmplot is one of the most important plots that should be able to do this because it requires a axeskeyword. But (with newly updated anaconda, matplotlib and seaborn) the following code: i

How to draw multiple plots in a for loop with warnings?

Yelanbo The structure of my code (just an example) is basically this: xs <- c("a","b") for(x in xs) { png(filename = paste(x,".png",sep="") ggplot() dev.off() } When I just run the code alone inside the loop, it produces a png file perfectly, but in Rstudio i

How to draw multiple plots in a for loop with warnings?

Yelanbo The structure of my code (just an example) is basically this: xs <- c("a","b") for(x in xs) { png(filename = paste(x,".png",sep="") ggplot() dev.off() } When I just run the code alone inside the loop, it produces a png file perfectly, but in Rstudio i

How to draw multiple plots in a for loop with warnings?

Yelanbo The structure of my code (just an example) is basically this: xs <- c("a","b") for(x in xs) { png(filename = paste(x,".png",sep="") ggplot() dev.off() } When I just run the code alone inside the loop, it produces a png file perfectly, but in Rstudio i

How to draw multiple plots in a for loop with warnings?

Yelanbo The structure of my code (just an example) is basically this: xs <- c("a","b") for(x in xs) { png(filename = paste(x,".png",sep="") ggplot() dev.off() } When I just run the code alone inside the loop, it produces a png file perfectly, but in Rstudio i

How to draw multiple plots in a for loop with warnings?

Yelanbo The structure of my code (just an example) is basically this: xs <- c("a","b") for(x in xs) { png(filename = paste(x,".png",sep="") ggplot() dev.off() } When I just run the code alone inside the loop, it produces a png file perfectly, but in Rstudio i

How to draw lines on plots?

Bubisi I'm trying to draw a line on a line, but the plot doesn't even show. I have checked the values of xPoints and yPoints and they exist. what is the reason? import matplotlib.pyplot as plt import numpy as np def calculateFuncFor(x): ePower = np.e**np.

How to draw lines on plots?

Bubisi I'm trying to draw a line on a line, but the plot doesn't even show. I have checked the values of xPoints and yPoints and they exist. what is the reason? import matplotlib.pyplot as plt import numpy as np def calculateFuncFor(x): ePower = np.e**np.

How to draw lines on plots?

Bubisi I'm trying to draw a line on a line, but the plot doesn't even show. I have checked the values of xPoints and yPoints and they exist. what is the reason? import matplotlib.pyplot as plt import numpy as np def calculateFuncFor(x): ePower = np.e**np.

How to draw a legend in R instead of multiple plots per window

brigadier I would like to place a common legend for my three plots where the fourth plot is (highlighted in yellow). How can I do this? Code to reproduce the plot par(mfrow = c(2, 2)) x <- rep(1:9, 3) y <- sample(1:9, 27, replace = T) group <- rep(1:3, each =

How to draw feather plots in R?

Tasan Is it possible to draw feather plots in R? Doing some Googling found only one R package ( ) that feather.plotcan make feather plots , but it's an old package that doesn't work with R version 3.6.1. Below is an example of a time series of wind speed and d

Matplotlib: how to draw contour plots?

year 1991 I have a function that I want to draw a contour plot: mixed_model_pdf([[x,y]]). It takes points [x,y]instead of X,Y as input. i.e. mixed_model_pdf([[-5,-5]]), ormixed_model_pdf([[-5,-5],[-5,-4]]) But to do this plt.contourf(X, Y, Z), Zthe values shou

How to draw feather plots in R?

Tasan Is it possible to draw feather plots in R? Doing some Googling found only one R package ( ) that feather.plotcan make feather plots , but it's an old package that doesn't work with R version 3.6.1. Below is an example of a time series of wind speed and d

How to draw feather plots in R?

Tasan Is it possible to draw feather plots in R? Doing some Googling found only one R package ( ) that feather.plotcan make feather plots , but it's an old package that doesn't work with R version 3.6.1. Below is an example of a time series of wind speed and d

Matplotlib: how to draw contour plots?

year 1991 I have a function that I want to draw a contour plot: mixed_model_pdf([[x,y]]). It takes points [x,y]instead of X,Y as input. i.e. mixed_model_pdf([[-5,-5]]), ormixed_model_pdf([[-5,-5],[-5,-4]]) But to do this plt.contourf(X, Y, Z), Zthe values shou