python繪圖之圖例的新增和座標軸的移動大法【轉】
阿新 • • 發佈:2019-01-29
轉自:https://blog.csdn.net/lishangyin88/article/details/80260957
1.圖例的新增
- import pandas as pd
- import numpy as np
- import matplotlib.pyplot as plt
- import matplotlib
- %matplotlib inline
- data1=np.random.normal(30,5,100)
- data2=np.random.normal(50,6,100)
- data3=np.random.normal(70,5,100)
- data4=np.random.rand(100)
- plt.plot(data1,label='label1'
- plt.plot(data2,label='label2')
- plt.plot(data3,label='label3')
- plt.plot(data4,label='label4')
- #bbox_to_anchor用於定位標籤的位置和大小。前兩個數值表示標籤左下角的座標,後兩個表示標籤的長度和高度
- #ncol表示標籤有幾列,loc表示位置0表示最合適。mode 表示是水平填充座標軸區域,
- #borderaxespad一般為預設,表示圖利與座標軸區域的空間。
- plt.legend(bbox_to_anchor=(0,1.02,1,0),ncol=2,loc=0,mode='expand',borderaxespad=
- #xy表示指向的位置座標,xytext表示註釋文字框的左下角的座標。
- plt.annotate('Important Value',xy=(18,20),xytext=(20,10),arrowprops=dict(arrowstyle='->'))
2.座標軸的移動
- x=np.linspace(-np.pi,np.pi,500,endpoint=True)
- y=np.sin(x)
- plt.plot(x,y)
- ax=plt.gca()
- #spines是指連線座標軸的線,一共有上下左右四個。top/bottom/right/left
- #上面的和右面的設定成無色
- ax.spines['right'].set_color(
- ax.spines['top'].set_color('none')
- #把下面的和左面的線設定成(0,0)
- ax.spines['bottom'].set_position(('data',0))
- ax.spines['left'].set_position(('data',0))
- ax.xaxis.set_ticks_position('bottom')
- #設定刻度間隔是0.5的倍數。這裡要注意引入matplotlib.
- ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))
- ax.ylim=(-1,1)