1. 程式人生 > >python畫雙y軸影象

python畫雙y軸影象

很多時候可能需要在一個圖中畫出多條函式影象,但是可能y軸的物理含義不一樣,或是數值範圍相差較大,此時就需要雙y軸。

matplotlib和seaborn都可以畫雙y軸影象。一個例子:

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()