1、雙y軸
x = np.arange(0., np.e, 0.01) y1 = np.exp(-x) y2 = np.log(x) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y1) ax1.set_ylabel('Y values for exp(-x)') ax1.set_title("Double Y axis") ax2 = ax1.twinx() # this is the important function ax2.plot(x, y2, 'r') ax2.set_xlim([0, np.e]) ax2.set_ylabel('Y values for ln(x)') ax2.set_xlabel('Same X for both exp(-x) and ln(x)') plt.show()
2、分段畫圖
def sgn(value): if value < 4: return 20 else: return 15 plt.figure(figsize=(6,4)) x = np.linspace(0, 8, 100) y = np.array([]) for v in x: y = np.append(y,np.linspace(sgn(v),sgn(v),1)) l=plt.plot(x,y,'b',label='type') plt.legend() plt.show()
3、繪制函數圖形及數值擬合
import matplotlib.pyplot as plt from scipy.optimize import curve_fit import numpy as np #用指數形式來擬合 x = np.arange(1, 17, 1) y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60]) def func(x,a,b): return a*np.exp(b/x) popt, pcov = curve_fit(func, x, y) a=popt[0]#popt里面是擬合系數,讀者可以自己help其用法 b=popt[1] yvals=func(x,a,b) plot1=plt.plot(x, y, '*',label='original values') plot2=plt.plot(x, yvals, 'r',label='curve_fit values') plt.xlabel('x axis') plt.ylabel('y axis') plt.legend(loc=4)#指定legend的位置,讀者可以自己help它的用法 plt.title('curve_fit') plt.show() plt.savefig('p2.png')
4.1、添加標簽
#使用自己下載的宋體庫simsun.ttc,原始matplotlib不支持中文 myfont = matplotlib.font_manager.FontProperties(fname="simsun.ttc") plt.rcParams['axes.unicode_minus'] = False dates,y1 = np.loadtxt('全國發病數據_可用於分析.csv', delimiter=',', usecols=(0,1), unpack=True) dates,y2 = np.loadtxt('全國發病數據_可用於分析.csv', delimiter=',', usecols=(0,2), unpack=True) plt.gcf().set_facecolor(np.ones(3) * 240/255)#設置背景色 fig, ax1 = plt.subplots() # 使用subplots()創建窗口 ax2 = ax1.twinx() # 創建第二個坐標軸 ax1.plot(dates, y1,'o-', c='orangered',label='y1', linewidth = 1) #繪制折線圖像1,圓形點,標簽,線寬 ax2.plot(dates, y2, 'o-', c='blue',label='y2', linewidth = 1) #同上 ax1.set_xlabel('時間', fontproperties=myfont,size=18) #與原始matplotlib設置參數略有不同,使用自己下載的中文宋體,參數位置不可改變 ax1.set_ylabel('第1列數據', fontproperties=myfont,size=18) ax2.set_ylabel('第2列數據', fontproperties=myfont,size=18) plt.gcf().autofmt_xdate()#自動適應刻度線密度,包括x軸,y軸 plt.legend()#顯示折線的意義 plt.show()
4.2、解決標簽不顯示的問題
fig, ax1 = plt.subplots() ax1.plot(dates, y1,'o-', c='orangered',label='cancer viliage num', linewidth = 1) plt.legend(loc=2) ax2 = ax1.twinx() ax2.plot(dates, y2, 'o-', c='blue',label='waster water', linewidth = 1) plt.legend(loc=1)
說明:在plt.legend()中添加了參數loc,而對應值1,2,3,4分別對應圖像的右上角,左上角,左下角,右下角
5、同一坐標畫圖
plt.figure(1)
x_axis = pd.to_datetime(data2['sample_time'],dayfirst=True).tolist() plt.plot(x_axis, data2['value'],"b-",label = '瞬時流量',linewidth = 2) plt.plot(x_axis,y3,"g-",label="均值",linewidth=2) plt.legend() plt.show()