Download the sample data here...
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
df = pd.read_csv(r'F:\Python\...\shampoo_sales.txt',
sep='\t',
header=0)
df['Month'] = pd.to_datetime(df['Month'])
color=[]
r = lambda: random.randint(0,255)
color.append('#%02X%02X%02X' % (r(),r(),r()))
y_pos = [i for i in range(len(df))]
y_label = [str(i)[0:7] for i in df['Month'].tolist()]
def autolabel_stack(rects, left=0, fontsize=10):
"""
Attach a text label above each bar displaying its height
"""
i=0
for rect in rects:
length = rect.get_width()
ax.text(left[i]+length/2,
rect.get_y(),
'%d' % int(length),
horizontalalignment ='center',
verticalalignment ='top',
fontsize=fontsize,
rotation=0,
color='white')
i+=1
width = 0.85
color=[]
for i in range(len(df)):
r = lambda: random.randint(0,255)
color.append('#%02X%02X%02X' % (r(),r(),r()))
fig, ax = plt.subplots(figsize=(10,7), dpi=100)
#ax.set_xlim([0, 815])
ax.spines['right'].set_visible(False)
#ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.xaxis.grid(b=False, which='major', color='gray', linestyle='--')
#ax.yaxis.grid(b=False, which='major', color='gray', linestyle='--')
lefts_01 = [0]*len(y_pos)
hbar1 = ax.barh(y_pos, df['Shampoo_Sales'], width, align='center',
color='#5291A2', ecolor='black',
label='Shampoo', left=lefts_01)
lefts_02 = lefts_01 + df['Shampoo_Sales']
hbar2 = ax.barh(y_pos, df['Other_Sales'], width, align='center',
color='#8F26EC', ecolor='black',
label='Other', left=lefts_02)
ax.set_yticks(y_pos)
ax.set_yticklabels(y_label)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Shampoo Sales')
ax.set_title('Shampoo Sales time vs. Sales')
ax.twinx()
ax.legend()
autolabel_stack(rects=hbar1, left=lefts_01, fontsize=8.5)
autolabel_stack(rects=hbar2, left=lefts_02, fontsize=8.5)
plt.show()
No comments:
Post a Comment