Issue
I have to create a program that calculate the average value for every rows in column 'total_revenue'
and that works, now that I have to plot the minimum of the average value and the max of the average value where the min value had to be red while the max value have to green, main problem is when I plotted them the result for both bar graph are red in red color, take a look at the code:
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_excel("C:\\users\\USER\\Documents\\dataset_file\\ad_table.xlsx",'ad_table')
data['avg_rev'] = data['total_revenue'].apply(lambda r: r/2)
min_avg_rev = data['avg_rev'].min()
max_avg_rev = data['avg_rev'].max()
best_ad = data[data['avg_rev'] == max_avg_rev]
worst_ad = data[data['avg_rev'] == min_avg_rev]
t0 = best_ad[['ad','avg_rev']].values
t1 = worst_ad[['ad','avg_rev']].values
result = pd.DataFrame({t0[0][0]: [t0[0][-1]],t1[0][0]: [t1[0][-1]]})
result = result.rename({0: 'avg_rev'})
plt.style.use('ggplot')
fig = plt.figure()
fig.set_figwidth(9)
fig.set_figheight(5)
col_val = []
for i in data['avg_rev']:
if i == max_avg_rev:
col_val.append('green')
elif i < max_avg_rev:
col_val.append('red')
plt.bar(t0[:,0],t0[:,-1],width=.5,color=col_val)
plt.bar(t1[:,0],t1[:,-1],width=.5,color=col_val)
plt.title('Result')
plt.xlabel('Group Name')
plt.ylabel('Avg. Revenue')
plt.show()
The dataframe of 'result'
:
ad_group_13 ad_group_23
avg_rev 19811.855 -100.075
The plotted graph:
Solution
The issue with colors appears to be in the plt.bar()
, where you are calling color=col_val
which is an array with 2 items, red and green. So, you should be calling col_val[0]
and col_val[1]
, so that the right color shows up.
Based on available data, I have simplified/modified your code to show the same below.
Code
avg_rev = pd.DataFrame({'ad_group_13' : [19811.855], 'ad_group_23' : [-100.075]})
plt.style.use('ggplot')
fig = plt.figure()
fig.set_figwidth(9)
fig.set_figheight(5)
col_val = ['green', 'red']
plt.bar(avg_rev.columns[0],avg_rev.iloc[0,0],width=.5,color=col_val[0])
plt.bar(avg_rev.columns[1],avg_rev.iloc[0,1],width=.5,color=col_val[1])
plt.title('Result')
plt.xlabel('Group Name')
plt.ylabel('Avg. Revenue')
plt.show()
Output plot
Answered By - Redox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.