1、條形圖
#!/usr/bin/env python3 #條形圖,表示一組分類數值 #導入pyplot模塊 import matplotlib.pyplot as plt #使用ggplot樣式模擬R語言中ggplot2的繪圖包 plt.style.use('ggplot') #為x軸准備數據 customers = ['ABC','DEF','GHI','JKL','MNO'] #計算X軸的長度 customers_index = range(len(customers)) #為y軸准備數據 sale_amounts = [127,90,201,111,232] #使用matplotlib繪圖時,首先要創建一個基礎圖 fig = plt.figure() #在基礎圖中添加了一個子圖,add_subplot(1,1,1)表示創建1行1列的子圖,並使用第一個子圖 ax1 = fig.add_subplot(1,1,1) #創建條形圖,customers_index設置條形圖左側在x軸上的坐標,sale_amounts設置條形圖的高度 #align='center'設置條形與標簽中間對齊,color='darkblue'設置條形的顏色 ax1.bar(customers_index,sale_amounts,align='center',color='darkblue') #設置刻度線位置在x軸的底部 ax1.xaxis.set_ticks_position('bottom') #設置刻度線位置在y軸的左側 ax1.yaxis.set_ticks_position('left') #將條形圖的刻度線標簽由客戶索引值更改為實際的客戶名稱 #rotation=0表示刻度標簽應該是水平的,而不是傾斜的。fontsize='small'將刻度標簽的字體設為小字體 plt.xticks(customers_index,customers,rotation=0,fontsize='small') #添加x軸標簽 plt.xlabel('Customer Name') #添加y軸標簽 plt.ylabel('Sale Name') #添加圖例標題 plt.title('Sale Amount per Customer') #將統計圖保存在指定文件夾中,名為bar_plot.png,dpi=400設置圖形分辨率(每英寸約2.54cm的點數) #bbox_inches='tight'表示保存圖形時,將圖形四周的空白部分去掉 plt.savefig('F://python入門//文件//bar_plot.png',dpi=400,bbox_inches='tight') #指示matplotlib在一個新窗口中顯示統計圖 plt.show()
結果:
本地中的bar_plot.png:
Spyder右下角顯示為:
2、直方圖
#!/usr/bin/env python3 #直方圖,表示數值分布 #numpy提供了多維數組(ndarray)數據類型 import numpy as np #導入pyplot模塊 import matplotlib.pyplot as plt #使用ggplot樣式模擬R語言中ggplot2的繪圖包 plt.style.use('ggplot') #為正太分布設置常量 mu1,mu2,sigma=100,130,15 #python隨機數生成器創建x1正太分布變量,均值為100 x1 = mu1+sigma*np.random.randn(10000) #python隨機數生成器創建x2正太分布變量,均值為130 x2 = mu2+sigma*np.random.randn(10000) #使用matplotlib繪圖時,首先要創建一個基礎圖 fig = plt.figure() #在基礎圖中添加了一個子圖,add_subplot(1,1,1)表示創建1行1列的子圖,並使用第一個子圖 ax1 = fig.add_subplot(1,1,1) #創建柱形圖,bins=50表示每個變量的值應該被分成50份,density=False表示直方圖顯示的是頻率分布, #而不是概率密度。color='darkgreen'直方圖顏色為暗綠色 n,bins,patches=ax1.hist(x1,bins=50,density=False,color='darkgreen') #創建柱形圖,color='darkgreen'直方圖顏色為橙色 n,bins,patches=ax1.hist(x2,bins=50,density=False,color='orange',alpha=0.5) #設置刻度線位置在x軸的底部 ax1.xaxis.set_ticks_position('bottom') #設置刻度線位置在y軸的左側 ax1.yaxis.set_ticks_position('left') #添加x軸標簽 plt.xlabel('Bins') #添加y軸標簽 plt.ylabel('Number of Values in Bin') #為基礎圖添加一個居中的標題,字體大小為14,粗體 fig.suptitle('Histogram',fontsize=14,fontweight='bold') #為子圖添加一個居中的標題,位於基礎圖標題下面 ax1.set_title('Two Frequency Distributions') #將統計圖保存在指定文件夾中,名為histogram.png,dpi=400設置圖形分辨率(每英寸約2.54cm的點數) #bbox_inches='tight'表示保存圖形時,將圖形四周的空白部分去掉 plt.savefig('F://python入門//文件//histogram.png',dpi=400,bbox_inches='tight') #指示matplotlib在一個新窗口中顯示統計圖 plt.show()
結果:
本地中的histogram.png:
Spyder右下角顯示為:
3、折線圖
#!/usr/bin/env python3 #折線圖 #導入隨機數模塊 from numpy.random import randn #導入pyplot模塊 import matplotlib.pyplot as plt #使用ggplot樣式模擬R語言中ggplot2的繪圖包 plt.style.use('ggplot') #cumsum()軸向元素累加和 plot_data1 = randn(50).cumsum() plot_data2 = randn(50).cumsum() plot_data3 = randn(50).cumsum() plot_data4 = randn(50).cumsum() #使用matplotlib繪圖時,首先要創建一個基礎圖 fig = plt.figure() #在基礎圖中添加了一個子圖,add_subplot(1,1,1)表示創建1行1列的子圖,並使用第一個子圖 ax1 = fig.add_subplot(1,1,1) #創建折線,marker表示折線類型,color顏色,linestyle線型,label為圖例 ax1.plot(plot_data1,marker=r'o',color=u'blue',linestyle='-',label='Blue Solid') ax1.plot(plot_data2,marker=r'+',color=u'red',linestyle='-',label='Red Dashed') ax1.plot(plot_data3,marker=r'*',color=u'green',linestyle='-',label='Green Dash Dot') ax1.plot(plot_data4,marker=r's',color=u'orange',linestyle='-',label='Orange Dotted') #設置刻度線位置在x軸的底部 ax1.xaxis.set_ticks_position('bottom') #設置刻度線位置在y軸的左側 ax1.yaxis.set_ticks_position('left') #為添加一個居中的標題 ax1.set_title('Line Plots:Markers,Color,and Linestyles') #添加x軸標簽 plt.xlabel('Draw') #添加y軸標簽 plt.ylabel('Random Number') #loc='best'指示matplotlib根據圖中的空白部分將圖例放在最合適的位置 plt.legend(loc='best') #bbox_inches='tight'表示保存圖形時,將圖形四周的空白部分去掉 plt.savefig('F://python入門//文件//line_plot.png',dpi=400,bbox_inches='tight') #指示matplotlib在一個新窗口中顯示統計圖 plt.show()
結果:
本地中的line_plot.png:
Spyder右下角顯示為:
4、散點圖
#!/usr/bin/env python3 #散點圖,表示兩個數值變量之間的關系 #numpy提供了多維數組(ndarray)數據類型 import numpy as np #導入pyplot模塊 import matplotlib.pyplot as plt #使用ggplot樣式模擬R語言中ggplot2的繪圖包 plt.style.use('ggplot') #構建x x = np.arange(start=1.,stop=15.,step=1.) #構建y1 y_liner = x + 5. * np.random.randn(14) #構建y2 y_quadratic = x**2 + 10.*np.random.randn(14) #使用polyfit函數通過兩組數據點擬合出一條直線 fn_liner = np.poly1d(np.polyfit(x,y_liner,deg=1)) #使用polyfit函數通過兩組數據點擬合出一條二次曲線 fn_quadratic = np.poly1d(np.polyfit(x,y_quadratic,deg=2)) #使用matplotlib繪圖時,首先要創建一個基礎圖 fig = plt.figure() #在基礎圖中添加了一個子圖,add_subplot(1,1,1)表示創建1行1列的子圖,並使用第一個子圖 ax1 = fig.add_subplot(1,1,1) #創建帶有兩條回歸曲線的散點圖 #'bo'藍色圓圈,'go'綠色圓圈,'b-'藍色實線,'g-'綠色實線,linewidth線的寬度 ax1.plot(x,y_liner,'bo',x,y_quadratic,'go',x,fn_liner(x),'b-',x,fn_quadratic(x),'g-',linewidth=2.) #設置刻度線位置在x軸的底部 ax1.xaxis.set_ticks_position('bottom') #設置刻度線位置在y軸的左側 ax1.yaxis.set_ticks_position('left') #為基礎圖添加一個居中的標題 ax1.set_title('Scatter Plots Regression Lines') #添加x軸標簽 plt.xlabel('x') #添加y軸標簽 plt.ylabel('f(x)') #設置X軸的范圍 plt.xlim(min(x)-1.,max(x)+1.) #設置Y軸的范圍 plt.ylim((min(y_quadratic)-10.,max(y_quadratic)+10.)) #將統計圖保存在指定文件夾中,名為scatter_plot.png,dpi=400設置圖形分辨率(每英寸約2.54cm的點數) #bbox_inches='tight'表示保存圖形時,將圖形四周的空白部分去掉 plt.savefig('F://python入門//文件//scatter_plot.png',dpi=400,bbox_inches='tight') #指示matplotlib在一個新窗口中顯示統計圖 plt.show()
結果:
本地中的scatter_plot.png:
Spyder右下角顯示為:
5、箱線圖
#!/usr/bin/env python3 #箱線圖,可以表示出數據的最小值、第一四分位數、中位數、第三四分位數和最大值。 #箱體的下部和上部邊緣線分別表示第一四分位數和第三四分位數,箱體的中間的直線表示中位數。 #箱體的上下兩端延伸出去的直線表示非離群點的最小值和最大值,在直線之外的點表示離群點 #numpy提供了多維數組(ndarray)數據類型 import numpy as np #導入pyplot模塊 import matplotlib.pyplot as plt #使用ggplot樣式模擬R語言中ggplot2的繪圖包 plt.style.use('ggplot') #設定一個常量 N = 500 #高斯隨機,loc=0.0對應概率分布的均值, #scale對應概率分布的標准差(對應於分布的寬度,scale越大越矮胖,scale越小,越瘦高) #size表示輸出的shape,默認為None,只輸出一個值 normal = np.random.normal(loc=0.0,scale=1.0,size=N) #對數正態分布,均值和標准差 lognormal = np.random.lognormal(mean=0.0,sigma=1.0,size=N) #生成閉區間[low,high]上離散均勻分布的整數值 index_value = np.random.random_integers(low=0,high=N-1,size=N) #高斯隨機 normal_sample = normal[index_value] #對數正態分布 lognormal_sample = lognormal[index_value] #將生成的目標數據放到列表中 box_plot_data = [normal,normal_sample,lognormal,lognormal_sample] #使用matplotlib繪圖時,首先要創建一個基礎圖 fig = plt.figure() #在基礎圖中添加了一個子圖,add_subplot(1,1,1)表示創建1行1列的子圖,並使用第一個子圖 ax1 = fig.add_subplot(1,1,1) #存放箱線圖的標簽 box_label = ['normal','normal_sample','lognormal','lognormal_sample'] #box_plot創建4個箱線圖,notch=False表示箱體是矩形,而不是中間收縮 #sym='.'表示離群點使用圓點,而不是默認的+號。vert=True表示箱體是垂直的,不是水平的 #whis=1.5設定了直線從第一四分位數和第三四分位數延伸出的范圍 #showmeans=True表示箱體在顯示中位數的同時也顯示均值lables=box_lable表示使用box_lable中的值來標記箱線圖 ax1.boxplot(box_plot_data,notch=False,sym='.',vert=True,whis=1.5,showmeans=True,labels=box_label) #設置刻度線位置在x軸的底部 ax1.xaxis.set_ticks_position('bottom') #設置刻度線位置在y軸的左側 ax1.yaxis.set_ticks_position('left') #為基礎圖添加一個居中的標題 ax1.set_title('Box Plots:Resampling of Two Distributions') #添加x軸標簽 ax1.set_xlabel('Distribution') #添加y軸標簽 ax1.set_ylabel('Value') #將統計圖保存在指定文件夾中,名為box_plot.png,dpi=400設置圖形分辨率(每英寸約2.54cm的點數) #bbox_inches='tight'表示保存圖形時,將圖形四周的空白部分去掉 plt.savefig('F://python入門//文件//box_plot.png',dpi=400,bbox_inches='tight') #指示matplotlib在一個新窗口中顯示統計圖 plt.show()
結果:
本地中的box_plot.png:
Spyder右下角顯示為:
6、組合圖
#!/usr/bin/env python3 #創建一個條形圖和箱線圖,並將它們並排放置 #引入pandas模塊,輔助繪圖 import pandas as pd #numpy提供了多維數組(ndarray)數據類型 import numpy as np #導入pyplot模塊 import matplotlib.pyplot as plt #使用ggplot樣式模擬R語言中ggplot2的繪圖包 plt.style.use('ggplot') #創建一個基礎圖和兩個並排放置的子圖 fig,axes=plt.subplots(nrows=1,ncols=2) #使用ravel()函數將兩個子圖分別賦給兩個變量ax1和ax2,這樣可以避免是使用行和列的索引 ax1,ax2 = axes.ravel() #創建一個數據框,存放5*3 data_frame = pd.DataFrame(np.random.rand(5,3),\ index=['Customer 1','Customer 2','Customer 3','Customer 4','Customer 5'],\ columns=pd.Index(['Metric 1','Metric 2','Metric 3'],name='Metric')) print(data_frame) #創建條形圖,在由句柄ax指定的軸框內繪圖,alpha是橫軸 data_frame.plot(kind='bar',ax=ax1,alpha=0.75,title='Bar Plot') #設置x軸的旋轉角度和字體,fontsize=10字體大小為10,旋轉角度為45度 plt.setp(ax1.get_xticklabels(),rotation=45,fontsize=10) #設置y軸的旋轉角度和字體 plt.setp(ax1.get_yticklabels(),rotation=0,fontsize=10) #添加x軸標簽 ax1.set_xlabel('Customer') #添加y軸標簽 ax1.set_ylabel('Value') #設置刻度線位置在x軸的底部 ax1.xaxis.set_ticks_position('bottom') #設置刻度線位置在y軸的左側 ax1.yaxis.set_ticks_position('left') #創建箱線圖並設置相關屬性 #創建一個顏色字典,箱體設置為深藍,將離群點的值設置為紅色 colors = dict(boxes='DarkBlue',whiskers='Gray',medians='Red',caps='Black') #繪制箱線圖 data_frame.plot(kind='box',color=colors,sym='r.',ax=ax2,title='Box Plot') #設置x軸的旋轉角度和字體 plt.setp(ax2.get_xticklabels(),rotation=45,fontsize=10) #設置y軸的旋轉角度和字體 plt.setp(ax2.get_yticklabels(),rotation=0,fontsize=10) #添加x軸標簽 ax2.set_xlabel('Metric') #添加y軸標簽 ax2.set_ylabel('Value') #設置刻度線位置在x軸的底部 ax2.xaxis.set_ticks_position('bottom') #設置刻度線位置在y軸的左側 ax2.yaxis.set_ticks_position('left') #將統計圖保存在指定文件夾中,名為pandas_plots.png,dpi=400設置圖形分辨率(每英寸約2.54cm的點數) #bbox_inches='tight'表示保存圖形時,將圖形四周的空白部分去掉 plt.savefig('F://python入門//文件//pandas_plots.png',dpi=400,bbox_inches='tight') #指示matplotlib在一個新窗口中顯示統計圖 plt.show()
結果:
本地中的pandas_plots.png:
Spyder右下角顯示為:
Metric Metric 1 Metric 2 Metric 3 Customer 1 0.727154 0.928098 0.876256 Customer 2 0.960446 0.262999 0.078873 Customer 3 0.630254 0.189192 0.776164 Customer 4 0.877072 0.182347 0.999244 Customer 5 0.471769 0.974709 0.399506