A series that adds cumulative ratios to the matplotlib
graph. Added cumulative ratio to bar chart. Click here for the completed plot
The point is that matplotlib.bar ()
can't specify categorical variables as they are for the name bar
, so I need to tell you where to plot on the x-axis. Specifically, numpy.arange ()
etc. is used to generate serial numbers and indexes for the number of categories and tell the location of the x-axis.
"""An example of adding a cumulative ratio to a maptlolib bar chart"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
#Plot cool in seaborn style
# % matplotlib inline
sns.set(style="darkgrid", palette="muted", color_codes=True)
#Toy data generation
df = pd.DataFrame({'group': ['A', 'B', 'C', 'D', 'E'],
'value': [20, 30, 10, 50, 40]})
#Specify x-axis plot position
#It needs to be generated because it does not do it without permission.
x_idx = np.arange(df.shape[0])
#Get fig and ax for plotting
fig, ax = plt.subplots()
#Added bar graph (1st axis)
bar = ax.bar(left=x_idx,
height=df['value'],
align='center',
tick_label=df['group'],
alpha=0.7
)
#Calculate the cumulative ratio for the 2nd axis
df['accumulative_ratio'] = df['value'].cumsum() / df['value'].sum()
#Added cumulative line graph to the 2nd axis
ax2 = ax.twinx()
line = ax2.plot(x_idx,
df['accumulative_ratio'],
ls='--',
marker='o',
color='r'
)
ax2.grid(visible=False)
plt.show()
The completed code with the legend etc. added is given in Gist.
Recommended Posts