Reputation: 542
I have a python script that parses a csv file and creates a mixed chart from it.
If the Current Progress has dropped since the Previous Progress by more than 5, I would like to change the color of the CurrentProg bar to red. Is it possible to do this?
For example, the table below is a sample of the csv file that I am parsing. I would like CurrentProg bar for Derick and Lisa to be red as shown in the graph below it.
Name OldProg PrevProg CurrentProg Goal
Derick 45 60 52 90
Jenna 56 87 89 90
Lisa 78 93 76 90
Harry 98 84 79 90
Here is a snippet of the code that parses the csv file and puts them into a bars/lines for the chart.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv("file.csv")
names = df['name'].values
x = np.arange(len(names))*2
w = 0.40
plt.bar(x-w, df['Old Progress'].values, width=w*0.7, label='OldProg', color = "cyan")
plt.bar(x, df['Previous Progress'].values, width=w*0.7, label='PrevProg', color = "green")
plt.bar(x+w, df['Current Progress'].values, width=w*0.7, label='CurrentProg', color = "blue")
plt.plot(x, df['Goal'].values, lw=2, label='Goal', color = "red")
Please let me know if I need to clarify anything further. Thank you.
Upvotes: 0
Views: 153
Reputation: 108
plt.bar()
can accept a list of colors with the same length as the number of items in the bar plot, rather than just a single color.
Thus, you can calculate the colors for each element in the bar plot, and pass that as the colors
parameter.
Something like this shoould do the trick:
df = pd.read_csv('test.csv')
progress_difference = df['CurrentProg'] - df['PrevProg']
colors = ['Red' if d < -5 else 'Grey' for d in progress_difference]
...
plt.bar(x+w, df['CurrentProg'].values, width=w*0.7,
label='CurrentProg', color = colors)
Upvotes: 1