Buy Me a Coffee? Your support is much appreciated!
demo.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv', index_col=0)
indx_order = np.arange(df.shape[0])
averages = {}
averages['Math Score'] = df['Math Score'].mean()
averages['Science Score'] = df['Science Score'].mean()
averages['English Score'] = df['English Score'].mean()
x_labels = df.columns
bar_width = 0.25
fig, ax = plt.subplots(figsize=(13, 6))
bar = {}
bar['Math Score'] = ax.bar(indx_order - bar_width, df['Math Score'], bar_width, label='Math', edgecolor='white',
color=['green' if v > averages['Math Score'] else 'red' for v in df['Math Score']])
bar['Science Score'] = ax.bar(indx_order - bar_width + 0.25, df['Science Score'], bar_width, label='Science', edgecolor='white',
color=['green' if v > averages['Science Score'] else 'red' for v in df['Science Score']])
bar['English Score'] = ax.bar(indx_order + bar_width, df['English Score'], bar_width, label='English', edgecolor='white',
color=['green' if v > averages['English Score'] else 'red' for v in df['English Score']])
ax.set_xticks(indx_order - bar_width + 0.25)
# place the labels
ax.set_xticklabels(df.index)
# insert legend
ax.legend(loc='upper right')
for bar_list in bar.values():
for bar_item in bar_list:
bar_height = bar_item.get_height()
print(bar_item.get_width())
ax.annotate(
'{0:.0f}'.format(bar_height),
xy=(bar_item.get_x(), bar_height),
xytext=(8, 1),
textcoords='offset points',
ha='center',
va='bottom'
)
plt.show()