plt.plot() 繪製折線圖數組
np.array() 將列表轉換爲存儲單一數據類型的多維數組,例如[1 2 3 4 5] app
zip(x,y) 函數用於將可迭代的對象做爲參數,將對象中對應的元素打包成一個個元組,而後返回由這些元組組成的對象,這樣作的好處是節約了很多的內 存。咱們可使用 list() 轉換來輸出列表。若是各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用*號操做符,能夠將元組解壓爲列表,例如a1,a2 = zip(*zip(a,b))。dom
plt.annotate() 給折線點設置(x,y)座標值ide
plt.tick_params() 設置刻度線和標籤的大小,顏色,內外側,both表明xy同時設置svg
plt.title()設置圖表標題函數
plt.xlabel() 設置X軸標籤spa
plt.ylabel() 設置Y軸標籤code
plt.axis([]) 設置X,Y軸刻度的取值範圍 orm
plt.savefig('') 保存圖表爲圖片格式對象
plt.show() 打開matplotlib查看器,並顯示繪製的圖形
#模塊pyplot包含不少生成圖表的函數 import matplotlib.pyplot as plt import numpy as np input_values = [1,2,3,4,5,6] squares = [1,4,9,16,25,36] #plot()繪製折線圖 plt.plot(input_values,squares,linewidth=5,color='m') #np.array()將列表轉換爲存儲單一數據類型的多維數組 x = np.array(input_values) y = np.array(squares) #annotate()給折線點設置座標值 for a,b in zip(x,y): plt.annotate('(%s,%s)'%(a,b),xy=(a,b),xytext=(-25,15), textcoords='offset points') #設置標題 plt.title('Square Numbers',fontsize=24) plt.xlabel('Value',fontsize=14) plt.ylabel('Square of Value',fontsize=14) #設置刻度線和標籤的大小,顏色,內外側,both表明xy同時設置 plt.tick_params(axis='both',direction='in',colors='c',labelsize=14) plt.axis([0,8,0,45]) plt.savefig('images\line_chart.png') #show()打開matplotlib查看器,並顯示繪製的圖形 plt.show()
plt.bar() 繪製直方圖
plt.text() 給條形柱添加標籤
import numpy as np import matplotlib.pyplot as plt #建立帶數字標籤的直方圖 numbers = list(range(1,11)) x = np.array(numbers) y = np.array([a**2 for a in numbers]) #繪製圖形 plt.bar(x,y,width=0.5,align='center',color='c') plt.title('Square Numbers',fontsize=24) plt.xlabel('Value',fontsize=14) plt.ylabel('Square of Value',fontsize=14) plt.tick_params(axis='both',labelsize=14) #設置xy軸座標取值範圍 plt.axis([0,11,0,110]) #設置標籤,a,b表明標籤的座標,第二個爲標籤內容,而後是對齊方式和尺寸 for a,b in zip(x,y): plt.text(a,b+0.1,'%.0f'%b,ha = 'center',va = 'bottom',fontsize=7) plt.savefig('images\squares.png') plt.show()
plt.scatter() 繪製散點圖
#scatter()繪製散點圖 import matplotlib.pyplot as plt x_values = list(range(1,11)) y_values = [x**2 for x in x_values] #參數c爲點的顏色,默認藍色;edgecolor爲點的輪廓顏色,默認黑色,none爲無色 plt.scatter(x_values,y_values,c='white',edgecolor='green',s=1000) ''' 還可使用RGB模式,向參數c傳遞一個元組,包含三個0-1之間的小數, 他們分別表明紅綠藍的分量,越接近0,顏色越深,越接近1,顏色越淺 c=(0,0,0.8),表明淡藍色 ''' #設置標題 plt.title('Square Numbers',fontsize=24) plt.xlabel('Value',fontsize=14) plt.ylabel('Square of Value',fontsize=14) #設置刻度的大小,both表明xy同時設置 plt.tick_params(axis='both',labelsize=14) #設置座標軸的取值範圍 plt.axis([0,11,-20,110]) #plt.savefig('images\squares_plot1.png') plt.show()
#根據每一個點的Y值來設置顏色映射 x_values = list(range(1,11)) y_values = [x**2 for x in x_values] '''參數c設置成Y值列表,表明各點的前後順序,使用參數camp告訴 pyplot使用什麼顏色映射,s爲點的大小 ''' plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Reds, edgecolor='green',s=1000) plt.title('Square Numbers',fontsize=24) plt.xlabel('Value',fontsize=14) plt.ylabel('Square of Value',fontsize=14) plt.tick_params(axis='both',labelsize=14) plt.axis([0,11,-20,110]) #savefig()自動保存圖表,第二個參數表示刪除圖表多餘的空白區域 plt.savefig('images\squares_plot2.png',bbox_inches='tight') plt.show()
randint(1,5) 從一個區間隨機返回一個數,包括兩端的數
hist = pygal.Bar() 定義直方圖類
hist.x_labels=[] 設置X軸刻度
hist.x_title='' X軸標題
hist.y_title='' Y軸標題
hist.add(' ',[]) 繪製直方圖,''內爲圖表標題
hist.render_to_file('') 保存到文件夾
#pygal模塊:建立可縮放的矢量圖形文件(.svg) import pygal from random import randint class Die(): def __init__(self,num_sides=6): self.num_sides = num_sides def roll(self): '''函數randint()返回一個區間的任意數值''' return randint(1,self.num_sides) #建立一個6面骰子,搖1000次,將結果存在列表中 die_1 = Die() die_2 = Die(10) results = [die_1.roll() + die_2.roll() for roll_num in range(5000)] #分析每一種結果的出現頻率,存在一個列表中 max_result = die_1.num_sides + die_2.num_sides frequencies = [results.count(value) for value in range(2,max_result+1)] #對結果進行可視化,hist:頻數直方圖 hist = pygal.Bar() hist.x_labels = list(range(2,max_result+1,1))#x軸刻度 hist.x_title = 'Result' # 標題 hist.y_title = 'Freqency of Rsult' #add()向它傳遞一個指定的標籤,一個列表,包含將出如今圖表中的值 hist.add('D6 + D10',frequencies) hist.render_to_file('images\hist.svg')
choice([])從列表中隨機輸出一個數
figure()用於指定圖表的寬度、高度、分辨率和背景色,形參figsize須要指定一個元組,單位爲英寸,dpi爲分辨率,facecolor爲窗口邊框顏色
plt.axes().get_xaxis().set_visible(False) 隱藏座標軸
line = pygal.Line() 繪製可縮放的折線圖
import matplotlib.pyplot as plt import pygal from random import choice class RandomWalk(): '''一個生成隨機漫步數據的類''' def __init__(self,num_points): self.num_points = num_points #全部的隨機漫步都始於(0,0) self.x_values = [0] self.y_values = [0] def get_step(self): direction = choice([1, -1]) # 隨機選擇向左向右兩個方向 distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8]) # 隨機選擇移動的距離 return direction * distance # 每次移動的步長 def fill_walk(self): '''定義一個循環,直到達到給定的點數''' while len(self.x_values) < self.num_points: x_step = self.get_step() y_step = self.get_step() #拒絕原地踏步 if x_step and y_step == 0: continue #計算下一個點的xy值,用列表的最後一個值加上步長 next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step self.x_values.append(next_x) self.y_values.append(next_y) rw = RandomWalk(5000) rw.fill_walk() #繪製特定窗口尺寸和分辨率的隨機漫步散點圖 plt.figure(figsize=(6,6),dpi=128,facecolor='palegreen') point_numbers = list(range(rw.num_points)) #以顏色映射的方式展現出來,能夠看出漫步中各點的前後順序 plt.scatter(rw.x_values,rw.y_values,c=point_numbers, cmap=plt.cm.Greens,edgecolor='none',s=1) #從新繪製第一個和最後一個點,突出顯示 plt.scatter(0,0,c='red',edgecolors='none',s=100) plt.scatter(rw.x_values[-1],rw.y_values[-1],c='orange', edgecolors='none',s=100) #exes()隱藏座標軸 plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) #plt.savefig(r'images\random_plot1.png') plt.show() '''生成隨機漫步折線圖''' rw = RandomWalk(5000) rw.fill_walk() plt.plot(rw.x_values,rw.y_values,color='cyan',linewidth=1) plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) plt.show() '''利用pygal實現隨機漫步折線圖''' lc = RandomWalk(5000) lc.fill_walk() line_chart = pygal.Line() line_chart.x_labels = map(str, range(0, 9)) line_chart.add('random',lc.y_values) line_chart.render_to_file(r'images\random.svg')