Home > OS >  How to draw a cumsum percent line-chart with a bar-chart?
How to draw a cumsum percent line-chart with a bar-chart?

Time:04-28

I want to draw a bar chart and want to sum them with cumsum percent, but I don't know how to do.

My sample code enter image description here

I want the bellow plot enter image description here

Can someone know how to do?

CodePudding user response:

If you plot them on the same axis, you can do it like this:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)


x = ['a', 'b', 'c']
y = np.array([115, 400, 200])
plt.bar(x, y)
ratio = y/y.sum()*100
cumsumRatio = ratio.cumsum()
ax.plot(x, cumsumRatio, color='orange')
for xy in zip(x, cumsumRatio):
    ax.annotate(f'({xy[1]:.2f}%)', xy=xy, textcoords='data')

enter image description here

Or on separate y axes:

import numpy as np
import matplotlib.pyplot as plt

fig, ax  = plt.subplots()
ax2 = ax.twinx()


x = ['a', 'b', 'c']
y = np.array([115, 400, 200])
ax.bar(x, y)
ratio = y/y.sum()*100
cumsumRatio = ratio.cumsum()
ax2.plot(x, cumsumRatio, color='orange')
for xy in zip(x, cumsumRatio):
    ax2.annotate(f'({xy[1]:.2f}%)', xy=xy, textcoords='data')

enter image description here

  • Related