matplotlib繪制直方圖的基本配置(萬能模板案例)
直方圖介紹
直方圖(Histogram),又稱質(zhì)量分布圖,是一種統(tǒng)計報告圖,由一系列高度不等的縱向條紋或線段表示數(shù)據(jù)分布的情況。 一般用橫軸表示數(shù)據(jù)類型,縱軸表示分布情況。
直方圖是數(shù)值數(shù)據(jù)分布的精確圖形表示。 這是一個連續(xù)變量(定量變量)的概率分布的估計,并且被卡爾·皮爾遜(Karl Pearson)首先引入。它是一種條形圖。
為了構(gòu)建直方圖,第一步是將值的范圍分段,即將整個值的范圍分成一系列間隔,然后計算每個間隔中有多少值。 這些值通常被指定為連續(xù)的,不重疊的變量間隔。 間隔必須相鄰,并且通常是(但不是必須的)相等的大小。
直方圖也可以被歸一化以顯示“相對”頻率。 然后,它顯示了屬于幾個類別中的每個案例的比例,其高度等于1。
繪制直方圖的參數(shù)(plt.hist())
通常而言,繪制直方圖有很多種方法,比如采用matplotlib里面的模塊進行繪制,也可以是pandas里面的圖形進行繪制,也可以使用Python里面其他的統(tǒng)計繪圖模塊進行繪制圖形,總而言之,想要圖形展示的美觀,那么就需要自己配置,也就是說模板固然重要,但是如果不懂原理的進行搬運和借用,反而效果不是很好!
連接數(shù)據(jù)庫進行直方圖繪制案例
# -*- coding: utf-8 -*- import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties mpl.rcParams['font.sans-serif']=['SimHei'] #顯示中文 plt.rcParams['axes.unicode_minus']=False #正常顯示負號 import pymysql #連接MySQL數(shù)據(jù)庫 v1 = [] v2 = [] db = pymysql.connect(host='127.0.0.1', port=3306, database='mydb',user='root',password='root') cursor = db.cursor() #讀取訂單表數(shù)據(jù),統(tǒng)計每日利潤額 sql_str = "SELECT order_date,ROUND(SUM(profit)/10000,2) FROM orders WHERE FY=2019 GROUP BY order_date" cursor.execute(sql_str) result = cursor.fetchall() for res in result: v1.append(res[0]) # order_date v2.append(res[1]) # sum_profit_by_order_date 每日利潤額 plt.figure(figsize=(10,5)) #設(shè)置圖形大小 cs,bs,bars = plt.hist(v2, bins=20, density=False, facecolor="cyan", edgecolor="black", alpha=0.7) width = bs[1]-bs[0] for i,c in enumerate(cs): plt.text(bs[i]+width/3,c,round(c)) # 返回一個counts數(shù)組,一個bins數(shù)組和一個圖形對象 # 顯示橫軸標簽 plt.xlabel("區(qū)間",fontdict={'family':'Fangsong','fontsize':15}) # 顯示縱軸標簽 plt.ylabel("頻數(shù)",fontdict={'family':'Fangsong','fontsize':15}) # 顯示圖標題 plt.title("利潤額分布直方圖",fontdict={'family':'Fangsong','fontsize':20}) plt.show()
使用dataframe里面的plot函數(shù)進行繪制(萬能模板)
一般而言,我們導(dǎo)入數(shù)據(jù)的時候,大概率都是基于表數(shù)據(jù)進行可視化的,很少使用那些自主獨立的數(shù)據(jù)進行繪制,如果是那種數(shù)據(jù),很多人都會去使用origin這個繪圖軟件了,程序繪圖最大的好處就是不需要對數(shù)據(jù)結(jié)果進行輸出,輸入,這樣在很大程度上減少了我們的時間,提高了我們的工作效率。
# 使用DataFrame的plot函數(shù)畫圖 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties mpl.rcParams['font.sans-serif']=['SimHei'] #顯示中文 plt.rcParams['font.sans-serif'] = 'KaiTi' # 設(shè)置全局字體為中文 楷體 plt.rcParams['axes.unicode_minus']=False #正常顯示負號 plt.figure(dpi=130) datafile = r'../data/orders.csv' data = pd.read_csv(datafile).query("FY==2019").groupby('ORDER_DATE')[['PROFIT']].sum() data.plot(kind='hist',bins=20,figsize=(15,5),color='y',alpha=0.5,edgecolor='c',histtype='bar') plt.xlabel("區(qū)間",fontdict={'family':'Fangsong','fontsize':15}) plt.ylabel("頻數(shù)",fontdict={'family':'Fangsong','fontsize':15}) plt.title("利潤額分布直方圖",fontdict={'family':'Fangsong','fontsize':20},y=1.03) # 設(shè)置圖形上的各類主題值 plt.suptitle('直方圖案例',size=22,y=1.05) plt.title("繪制日期:2022年 昵稱:王小王-123", loc='right',size=12,y=1.03) plt.title("主頁:https://blog.csdn.net/weixin_47723732", loc='left',size=12,y=1.03) plt.show()
繪制多個子圖(多子圖直方圖案例模板)
plt.tight_layout() # 自動緊湊布局,避免遮擋
是很重要的一個參數(shù),一般是在結(jié)尾出添加這個參數(shù)
import pandas as pd datafile = r'../data/orders.csv' data = pd.read_csv(datafile).query("FY==2019").groupby('ORDER_DATE')[['PROFIT']].sum() fig = plt.figure(figsize=(10,5),dpi=130) # 生成畫布 # 生成子圖1 ax1 = plt.subplot(121) # 1行2列中的第1個 plt.title("CSDN博客專家", loc='left',size=12,y=1.03) #添加備注 # 生成子圖2 ax2 = plt.subplot(122) # 1行2列中的第2個 # 設(shè)置圖形上的各類主題值 plt.title("王小王-123", loc='right',size=12,y=1.03)#添加備注 #df.plot使figure級別的繪圖函數(shù),默認會生成新的figure,可以通過ax參數(shù)指定繪圖的坐標子圖 data.plot(kind='hist',bins=20,color='c',alpha=0.5,edgecolor='c',histtype='bar',ax=ax1,figure=fig) # 指定這個圖畫到ax1中 #plt.xlabel("區(qū)間",fontdict={'family':'Fangsong','fontsize':15}) ax1.set_xlabel("區(qū)間",fontdict={'family':'Fangsong','fontsize':15}) #plt.ylabel("頻數(shù)",fontdict={'family':'Fangsong','fontsize':15}) ax1.set_ylabel("頻數(shù)",fontdict={'family':'Fangsong','fontsize':15}) ax1.set_title("cyan") #print(ax1.get_xticks()) data.plot(kind='hist',bins=20,color='y',alpha=0.5,edgecolor='y',histtype='bar',ax=ax2,figure=fig) # 指定這個圖畫到ax2中 # plt.xlabel = plt.gca().set_xlabel() plt. 獲取“當(dāng)前”的坐標子圖,需要小心執(zhí)行的位置 plt.xlabel("區(qū)間",fontdict={'family':'Fangsong','fontsize':15}) plt.ylabel("頻數(shù)",fontdict={'family':'Fangsong','fontsize':15}) plt.title("yellow") # subplot的標題 plt.suptitle("利潤額分布直方圖",fontdict={'family':'Fangsong','size':22}) # figure的標題 plt.tight_layout() # 自動緊湊布局,避免遮擋 plt.show()
概率分布直方圖(統(tǒng)計圖形)
# -*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt #概率分布直方圖 #高斯分布 #均值為0 mean = 0 #標準差為1,反應(yīng)數(shù)據(jù)集中還是分散的值 sigma = 1 x=mean+sigma*np.random.randn(10000) fig,(ax0,ax1) = plt.subplots(nrows=2,figsize=(9,6)) #第二個參數(shù)是柱子寬一些還是窄一些,越大越窄越密 ax0.hist(x,40,density=1,histtype='bar',facecolor='yellowgreen',alpha=0.75) # histtype返回一組bar的數(shù)組 ##pdf概率分布圖,一萬個數(shù)落在某個區(qū)間內(nèi)的數(shù)有多少個 ax0.set_title('pdf') ax1.hist(x,20,density=1,histtype='stepfilled',facecolor='pink',alpha=0.75,cumulative=True,rwidth=0.8) # 返回的一條step線,cumulative=True數(shù)值的累積的 #cdf累計概率函數(shù),cumulative累計。比如需要統(tǒng)計小于5的數(shù)的概率 ax1.set_title("cdf") fig.subplots_adjust(hspace=0.4) plt.show()
直方圖內(nèi)顯示折線圖分布
import matplotlib.mlab as mlab import matplotlib.pyplot as plt mpl.rcParams['font.sans-serif']=['SimHei'] #顯示中文 plt.rcParams['font.sans-serif'] = 'KaiTi' # 設(shè)置全局字體為中文 楷體 plt.rcParams['axes.unicode_minus']=False #正常顯示負號 plt.figure(figsize=(17,8),dpi=120) import numpy as np from scipy.stats import norm np.random.seed(10680801) mu=100 sigma=15 x=mu+sigma*np.random.randn(500) num_bins=60 fig,ax=plt.subplots() #fig,ax=plt.subplots(ncols=2) #ax1 = ax[0] #ax2 = ax[1] n,bins,patches=ax.hist(x,num_bins,density=True) y=norm.pdf(bins,mu,sigma) ax.plot(bins,y,'--') ax.set_xlabel('IQ') ax.set_ylabel('概率密度') ax.set_title(r'智商分布情況直方圖') fig.tight_layout()
堆疊面積直方圖
import numpy as np import pandas as pd from matplotlib import pyplot as plt crime=pd.read_csv(r"http://datasets.flowingdata.com/crimeRatesByState2005.csv") fig,ax=plt.subplots() ax.hist(crime["robbery"],bins=12,histtype="bar",alpha=0.6,label="robbery",stacked=True) ax.hist(crime["aggravated_assault"],bins=12,histtype="bar",alpha=0.6,label="aggravated_assault",stacked=True) ax.legend() ax.set_xticks(np.arange(0,721,60)) ax.set_xlim(0,720) ax.set_yticks(np.arange(0,21,4)) plt.show()
在不同的子圖中繪制各種類犯罪數(shù)據(jù)的數(shù)值分布
import numpy as np import pandas as pd from matplotlib import pyplot as plt crime=pd.read_csv(r"http://datasets.flowingdata.com/crimeRatesByState2005.csv") crime = crime.query("state!='United States'").query("state!='District of Columbia'") plt.figure(figsize=(10,5),dpi=120) nrows=2 ncols=4 n = np.arange(nrows*ncols)+1 for i in n: ax = plt.subplot(nrows,ncols,i) ax.hist(crime.iloc[:,i]) ax.set_title(crime.columns[i]) plt.suptitle("各種類犯罪數(shù)據(jù)的數(shù)值分布",y=1.02) plt.tight_layout()
其他案例
乘客年齡分布頻數(shù)直方圖
# 導(dǎo)入第三方庫 import pandas as pd import matplotlib.pyplot as plt # 設(shè)置中文 plt.rcParams['font.sans-serif'] = ['SimHei'] # 創(chuàng)建圖形 plt.figure(figsize=(20,8),dpi=80) # 準備數(shù)據(jù)(讀取Titanic數(shù)據(jù)集) titanic = pd.read_csv(r'E:\PythonData\exercise_data\train.csv') # 檢查年齡是否有缺失 any(titanic.Age.isnull()) # 刪除含有缺失年齡的觀察 titanic.dropna(subset=['Age'], inplace=True) # 繪圖:乘客年齡的頻數(shù)直方圖 plt.hist(titanic.Age, # 繪圖數(shù)據(jù) bins = 20, # 指定直方圖的條形數(shù)為20個 color = 'steelblue', # 指定填充色 edgecolor = 'k', # 設(shè)置直方圖邊界顏色 label = '直方圖' )# 為直方圖呈現(xiàn)標簽 # 刻度設(shè)置 plt.xticks(fontsize=15) plt.yticks(fontsize=15) # 添加描述信息 plt.xlabel('年齡:歲',fontsize=20) plt.ylabel('人數(shù):個',fontsize=20) plt.title('乘客年齡分布',fontsize=20) # 顯示圖形 plt.show()
男女乘客直方圖(二維數(shù)據(jù))
設(shè)置了組距和其他的參數(shù)
# 導(dǎo)入庫 import matplotlib.pyplot as plt import numpy as np # 設(shè)置字體 plt.rcParams['font.sans-serif'] = ['SimHei'] # 創(chuàng)建圖形 plt.figure(figsize=(20,8),dpi=80) # 提取不同性別的年齡數(shù)據(jù) age_female = titanic.Age[titanic.Sex == 'female'] age_male = titanic.Age[titanic.Sex == 'male'] # 設(shè)置直方圖的組距 bins = np.arange(titanic.Age.min(), titanic.Age.max(), 2) # 男性乘客年齡直方圖 plt.hist(age_male, bins = bins, label = '男性',edgecolor = 'k', color = 'steelblue', alpha = 0.7) # 女性乘客年齡直方圖 plt.hist(age_female, bins = bins, label = '女性',edgecolor = 'k', alpha = 0.6,color='r') # 調(diào)整刻度 plt.xticks(fontsize=15) plt.yticks(fontsize=15) # 設(shè)置坐標軸標簽和標題 plt.title('男女乘客年齡直方圖',fontsize=20) plt.xlabel('年齡',fontsize=20) plt.ylabel('人數(shù)',fontsize=20) # 去除圖形頂部邊界和右邊界的刻度 plt.tick_params(top='off', right='off') # 顯示圖例 plt.legend(loc='best',fontsize=20) # 顯示圖形 plt.show()
電影時長分布直方圖
# 導(dǎo)入庫 import matplotlib.pyplot as plt # 設(shè)置字體 plt.rcParams['font.sans-serif'] = ['SimHei'] # 創(chuàng)建圖形 plt.figure(figsize=(20,8),dpi=80) # 準備數(shù)據(jù) time=[131,98,125,131,124,139,131,117,128,108,135,138,131,102,107,114,119,128,121,142,127,130,124,101,110,116,117,110,128,128,115,99,136,126, 134,95,138,117,111,78,132,124,113,150,110,117,86,95,144,105,126,130,126,130,126,116,123,106,112,138,123,86,101,99,136,123,117,119,105, 137,123,128,125,104,109,134,125,127,105,120,107,129,116,108,132,103,136,118,102,120,114,105,115,132,145,119,121,112,139,125,138,109, 132,134,156,106,117,127,144,139,139,119,140,83,110,102,123,107,143,115,136,118,139,123,112,118,125,109,119,133,112,114,122,109,106, 123,116,131,127,115,118,112,135,115,146,137,116,103,144,83,123,111,110,111, 100,154,136,100,118,119,133,134,106,129,126,110,111,109, 141,120,117,106,149,122,122,110,118,127,121,114,125,126,114,140,103,130,141,117,106,114,121,114,133,137,92,121,112,146,97,137,105,98, 117,112,81,97,139,113,134,106,144,110,137,137,111,104,117,100,111,101,110,105,129,137,112,120,113,133,112,83,94,146, 133,101,131,116, 111, 84,137,115,122,106,144,109,123,116,111,111,133,150] # 設(shè)置組距 bins=2 groups = int((max(time)-min(time))/bins) # 繪制直方圖 plt.hist(time,groups,color='b', edgecolor = 'k', density = True) # 指定直方從圖的邊界色) # 調(diào)整刻度 plt.xticks(list(range(min(time),max(time)))[::2],fontsize=15) plt.yticks(fontsize=15) # 添加描述信息 plt.xlabel('電影時長:分鐘',fontsize=20) plt.ylabel('電影數(shù)量占比',fontsize=20) # 增加網(wǎng)格 plt.grid(True,linestyle='--',alpha=1) # 添加標題 plt.title('電影時長分布直方圖',fontsize=20) plt.show()
到此這篇關(guān)于matplotlib繪制直方圖的基本配置(萬能模板案例)的文章就介紹到這了,更多相關(guān)matplotlib 直方圖 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Matplotlib直方圖繪制中的參數(shù)bins和rwidth的實現(xiàn)
本文主要介紹了Matplotlib直方圖繪制中的參數(shù)bins和rwidth的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02python實現(xiàn)類似ftp傳輸文件的網(wǎng)絡(luò)程序示例
這篇文章主要介紹了python實現(xiàn)類似ftp傳輸文件的網(wǎng)絡(luò)程序示例,需要的朋友可以參考下2014-04-04anaconda安裝pytorch1.7.1和torchvision0.8.2的方法(親測可用)
這篇文章主要介紹了anaconda安裝pytorch1.7.1和torchvision0.8.2的方法(親測可用),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02Conda中環(huán)境遷移到另一個服務(wù)器的實現(xiàn)
本文主要介紹了Conda中的環(huán)境遷移到另一個服務(wù)器,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03PyQt QListWidget修改列表項item的行高方法
今天小編就為大家分享一篇PyQt QListWidget修改列表項item的行高方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python調(diào)用edge-tts實現(xiàn)在線文字轉(zhuǎn)語音效果
edge-tts是一個 Python 模塊,允許通過Python代碼或命令的方式使用 Microsoft Edge 的在線文本轉(zhuǎn)語音服務(wù),這篇文章主要介紹了Python調(diào)用edge-tts實現(xiàn)在線文字轉(zhuǎn)語音效果,需要的朋友可以參考下2024-03-03OpenCV圖像識別之姿態(tài)估計Pose?Estimation學(xué)習(xí)
這篇文章主要為大家介紹了OpenCV圖像識別之姿態(tài)估計Pose?Estimation學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05