Example code of python drawing double y axis image

  • 2021-07-10 20:16:48
  • OfStack

In many cases, it may be necessary to draw multiple function images in one diagram, but the physical meaning of y axis is different, or the numerical range is quite different, so double y axis is needed.

Both matplotlib and seaborn can draw double y axis images.

1 example:


import seaborn as sns
import matplotlib.pyplot as plt
 
# ax1 for KDE, ax2 for CDF
 
f, ax1 = plt.subplots()
ax1.grid(True)
# ax1.set_ylim(0, 1)
ax1.set_ylabel('KDE')
ax1.set_xlabel('DATA')
ax1.set_title('KDE + CDF')
ax1.legend(loc=2)
sns.kdeplot(data, ax=ax1, lw=2, label='KDE') # KDE
 
ax2 = ax1.twinx() # the reason why it works
ax2.set_ylabel('CDF')
ax2.legend(loc=1)
ax2.hist(data, bins=50, cumulative=True, normed=True, histtype='step', color='red', lw=2, label='CDF') # CDF
 
plt.show()

Related articles: