1. 程式人生 > >python繪圖之圖例的新增和座標軸的移動大法【轉】

python繪圖之圖例的新增和座標軸的移動大法【轉】

轉自:https://blog.csdn.net/lishangyin88/article/details/80260957

1.圖例的新增

  1. import pandas as pd  
  2. import numpy as np  
  3. import matplotlib.pyplot as plt  
  4. import matplotlib  
  5. %matplotlib inline  
  6. data1=np.random.normal(30,5,100)  
  7. data2=np.random.normal(50,6,100)  
  8. data3=np.random.normal(70,5,100)  
  9. data4=np.random.rand(100)  
  10. plt.plot(data1,label='label1'
    )  
  11. plt.plot(data2,label='label2')  
  12. plt.plot(data3,label='label3')  
  13. plt.plot(data4,label='label4')  
  14. #bbox_to_anchor用於定位標籤的位置和大小。前兩個數值表示標籤左下角的座標,後兩個表示標籤的長度和高度
  15. #ncol表示標籤有幾列,loc表示位置0表示最合適。mode 表示是水平填充座標軸區域,
  16. #borderaxespad一般為預設,表示圖利與座標軸區域的空間。
  17. plt.legend(bbox_to_anchor=(0,1.02,1,0),ncol=2,loc=0,mode='expand',borderaxespad=
    0)  
  18. #xy表示指向的位置座標,xytext表示註釋文字框的左下角的座標。
  19. plt.annotate('Important Value',xy=(18,20),xytext=(20,10),arrowprops=dict(arrowstyle='->'))  

2.座標軸的移動

  1. x=np.linspace(-np.pi,np.pi,500,endpoint=True)  
  2. y=np.sin(x)  
  3. plt.plot(x,y)  
  4. ax=plt.gca()  
  5. #spines是指連線座標軸的線,一共有上下左右四個。top/bottom/right/left
  6. #上面的和右面的設定成無色
  7. ax.spines['right'].set_color(
    'none')  
  8. ax.spines['top'].set_color('none')  
  9. #把下面的和左面的線設定成(0,0)
  10. ax.spines['bottom'].set_position(('data',0))  
  11. ax.spines['left'].set_position(('data',0))  
  12. ax.xaxis.set_ticks_position('bottom')  
  13. #設定刻度間隔是0.5的倍數。這裡要注意引入matplotlib.
  14. ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))  
  15. ax.ylim=(-1,1)