欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python進(jìn)階Matplotlib庫(kù)圖繪制

 更新時(shí)間:2022年07月03日 16:36:08   作者:隨緣清風(fēng)殤  
這篇文章主要介紹了Python進(jìn)階Matplotlib庫(kù)圖繪制,Matplotlib:是一個(gè)Python的2D繪圖庫(kù),通過(guò)Matplotlib,開(kāi)發(fā)者可以僅需要幾行代碼,便可以生成折線圖,直方圖,條形圖,餅狀圖,散點(diǎn)圖等

中文字體設(shè)置:

# 字體設(shè)置
plt.rcParams['font.sans-serif'] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

1、基本使用

Matplotlib:是一個(gè)Python的2D繪圖庫(kù),通過(guò)Matplotlib,開(kāi)發(fā)者可以僅需要幾行代碼,便可以生成折線圖,直方圖,條形圖,餅狀圖,散點(diǎn)圖等。
plot是一個(gè)畫(huà)圖的函數(shù),他的參數(shù):plot([x],y,[fmt],data=None,**kwargs)

1.1、線條樣式 & 顏色

(1)點(diǎn)線形式

(2)線條顏色

import matplotlib.pyplot as plt
import numpy as np
# 原始線圖
plt.plot(range(10),[np.random.randint(0,10) for x in range(10)])
# 點(diǎn)線圖
plt.plot(range(10),[np.random.randint(0,10) for x in range(10)],"*")
# 線條顏色
plt.plot([1,2,3,4,5],[1,2,3,4,5],'r') #將顏色線條設(shè)置成紅色

運(yùn)行結(jié)果:

1.2、軸&標(biāo)題

  • 1、設(shè)置圖標(biāo)題:plt.title
  • 2、設(shè)置軸標(biāo)題:plt.xlabel & plt.ylabel  -  標(biāo)題名稱
  • 3、設(shè)置軸刻度:plt.xticks & plt.yticks  -  刻度長(zhǎng)度,刻度標(biāo)題

范例:

x = range(10)
y = [np.random.randint(0,10) for x in range(10)]
plt.plot(x,y,linewidth=10,color='red')
# 設(shè)置圖標(biāo)題
plt.title("sin函數(shù)")
# 設(shè)置軸標(biāo)題
plt.xlabel("x軸")
plt.ylabel("y軸")
# 設(shè)置軸刻度
plt.xticks(range(10),["第%d天"%x for x in range(1,10)])
plt.yticks(range(10),["第%d天"%x for x in range(1,10)])
# 加載字體
plt.rcParams['font.sans-serif'] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

運(yùn)行結(jié)果:

1.3、marker設(shè)置

marker:關(guān)鍵點(diǎn)重點(diǎn)標(biāo)記

范例:

x = range(10)
y = [np.random.randint(0,10) for x in range(10)]
plt.plot(x,y,linewidth=10,color='red')
# 重點(diǎn)標(biāo)記
plt.plot(x,y,marker="o",markerfacecolor='k',markersize=10)

運(yùn)行結(jié)果:

1.4、注釋文本

annotate:注釋文本

范例:

x = range(10)
y = [np.random.randint(0,10) for x in range(10)]
plt.plot(x,y,linewidth=10,color='red')
# 重點(diǎn)標(biāo)記
plt.plot(x,y,marker="o",markerfacecolor='k',markersize=10)

# 注釋文本設(shè)置
plt.annotate('local max', xy=(5, 5), xytext=(10,15),
arrowprops=dict(facecolor='black',shrink=0.05),
)

運(yùn)行結(jié)果:

1.5、設(shè)置圖形樣式

plt.figure:調(diào)整圖片的大小和像素
	`num`:圖的編號(hào),
	`figsize`:單位是英寸,
	`dpi`:每英寸的像素點(diǎn),
	`facecolor`:圖片背景顏色,
	`edgecolor`:邊框顏色,
	`frameon`:是否繪制畫(huà)板。  

范例:

x = range(10)
y = [np.random.randint(0,10) for x in range(10)]
# 設(shè)置圖形樣式
plt.figure(figsize=(20,10),dpi=80)
plt.plot(x,y,linewidth=10,color='red')

運(yùn)行結(jié)果:

2、條形圖

應(yīng)用場(chǎng)景:

  • 1. 數(shù)量統(tǒng)計(jì)。
  • 2. 頻率統(tǒng)計(jì)。

相關(guān)參數(shù):

barh:條形圖

  • 1. `x`:一個(gè)數(shù)組或者列表,代表需要繪制的條形圖的x軸的坐標(biāo)點(diǎn)。  
  • 2. `height`:一個(gè)數(shù)組或者列表,代表需要繪制的條形圖y軸的坐標(biāo)點(diǎn)。  
  • 3. `width`:每一個(gè)條形圖的寬度,默認(rèn)是0.8的寬度。  
  • 4. `bottom`:`y`軸的基線,默認(rèn)是0,也就是距離底部為0.  
  • 5. `align`:對(duì)齊方式,默認(rèn)是`center`,也就是跟指定的`x`坐標(biāo)居中對(duì)齊,還有為`edge`,靠邊對(duì)齊,具體靠右邊還是靠左邊,看`width`的正負(fù)。  
  • 6. `color`:條形圖的顏色。

2.1、橫向條形圖 范例

movies = {
    "流浪地球":40.78,
    "飛馳人生":15.77,
    "瘋狂的外星人":20.83,
    "新喜劇之王":6.10,
    "廉政風(fēng)云":1.10,
    "神探蒲松齡":1.49,
    "小豬佩奇過(guò)大年":1.22,
    "熊出沒(méi)·原始時(shí)代":6.71
}
plt.barh(np.arange(len(movies)),list(movies.values()))
plt.yticks(np.arange(len(movies)),list(movies.keys()),fontproperties=font)
plt.grid()

運(yùn)行結(jié)果:

2.2、分組條形圖

范例:

movies = {
    "流浪地球":[2.01,4.59,7.99,11.83,16],
    "飛馳人生":[3.19,5.08,6.73,8.10,9.35],
    "瘋狂的外星人":[4.07,6.92,9.30,11.29,13.03],
    "新喜劇之王":[2.72,3.79,4.45,4.83,5.11],
    "廉政風(fēng)云":[0.56,0.74,0.83,0.88,0.92],
    "神探蒲松齡":[0.66,0.95,1.10,1.17,1.23],
    "小豬佩奇過(guò)大年":[0.58,0.81,0.94,1.01,1.07],
    "熊出沒(méi)·原始時(shí)代":[1.13,1.96,2.73,3.42,4.05]
}
plt.figure(figsize=(20,8))
width = 0.75
bin_width = width/5
movie_pd = pd.DataFrame(movies)
ind = np.arange(0,len(movies))

# 第一種方案
for index in movie_pd.index:
    day_tickets = movie_pd.iloc[index]
    xs = ind-(bin_width*(2-index))
    plt.bar(xs,day_tickets,width=bin_width,label="第%d天"%(index+1))
    for ticket,x in zip(day_tickets,xs):
        plt.annotate(ticket,xy=(x,ticket),xytext=(x-0.1,ticket+0.1))
# 設(shè)置圖例
plt.ylabel("單位:億")
plt.title("春節(jié)前5天電影票房記錄")
# 設(shè)置x軸的坐標(biāo)
plt.xticks(ind,movie_pd.columns)
plt.xlim
plt.grid(True)
plt.show()

運(yùn)行結(jié)果:

2.3、堆疊條形圖

范例:

menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
groupNames = ('G1','G2','G3','G4','G5')
xs = np.arange(len(menMeans))
plt.bar(xs,menMeans)
plt.bar(xs,womenMeans,bottom=menMeans)
plt.xticks(xs,groupNames)
plt.show()

運(yùn)行結(jié)果:

3、直方圖

plt.hist:直方圖

  • 1. x:數(shù)組或者可以循環(huán)的序列;
  • 2. bins:數(shù)字或者序列(數(shù)組/列表等);
  • 3. range:元組或者None,如果為元組,那么指定`x`劃分區(qū)間的最大值和最小值;
  • 4. density:默認(rèn)是`False`,如果等于`True`,那么將會(huì)使用頻率分布直方圖;
  • 5. cumulative:如果這個(gè)和`density`都等于`True`,那么返回值的第一個(gè)參數(shù)會(huì)不斷的累加,最終等于`1`。

應(yīng)用場(chǎng)景:

  • 1. 顯示各組數(shù)據(jù)數(shù)量分布的情況。
  • 2. 用于觀察異?;蚬铝?shù)據(jù)。
  • 3. 抽取的樣本數(shù)量過(guò)小,將會(huì)產(chǎn)生較大誤差,可信度低,也就失去了統(tǒng)計(jì)的意義。因此,樣本數(shù)不應(yīng)少于50個(gè)。

3.1、直方圖

范例:

durations = [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]
plt.figure(figsize=(15,5))
nums,bins,patches = plt.hist(durations,bins=20,edgecolor='k')
plt.xticks(bins,bins)
for num,bin in zip(nums,bins):
    plt.annotate(num,xy=(bin,num),xytext=(bin+1.5,num+0.5))
plt.show()

運(yùn)行結(jié)果:

3.2、頻率直方圖

density:頻率直方分布圖

范例:

nums,bins,patches = plt.hist(durations,bins=20,edgecolor='k',density=True,cumulative=True)
plt.xticks(bins,bins)
for num,bin in zip(nums,bins):
    plt.annotate("%.4f"%num,xy=(bin,num),xytext=(bin+0.2,num+0.0005))

運(yùn)行結(jié)果:

3.3、直方圖

cumulative參數(shù):nums的總和為1

范例:

plt.figure(figsize=(15,5))
nums,bins,patches = plt.hist(durations,bins=20,edgecolor='k',density=True,cumulative=True)
plt.xticks(bins,bins)
for num,bin in zip(nums,bins):
    plt.annotate("%.4f"%num,xy=(bin,num),xytext=(bin+0.2,num+0.0005))

運(yùn)行結(jié)果:

4、散點(diǎn)圖

plt.scatter:散點(diǎn)圖繪制:

  • 1. x,y:分別是x軸和y軸的數(shù)據(jù)集。兩者的數(shù)據(jù)長(zhǎng)度必須一致。
  • 2. s:點(diǎn)的尺寸。
  • 3. c:點(diǎn)的顏色。
  • 4. marker:標(biāo)記點(diǎn),默認(rèn)是圓點(diǎn),也可以換成其他的。

范例:

plt.scatter(x =data_month_sum["sumprice"]     #傳入X變量數(shù)據(jù)
            ,y=data_month_sum["Quantity"]     #傳入Y變量數(shù)據(jù)
            ,marker='*'     #點(diǎn)的形狀
            ,s=10           #點(diǎn)的大小
            ,c='r'          #點(diǎn)的顏色
           )
plt.show()

運(yùn)行結(jié)果:

5、餅圖

餅圖:一個(gè)劃分為幾個(gè)扇形的圓形統(tǒng)計(jì)圖表,用于描述量、頻率或百分比之間的相對(duì)關(guān)系的。

matplotlib中,可以通過(guò)plt.pie來(lái)實(shí)現(xiàn),其中的參數(shù)如下:

x:餅圖的比例序列。labels:餅圖上每個(gè)分塊的名稱文字。explode:設(shè)置某幾個(gè)分塊是否要分離餅圖。autopct:設(shè)置比例文字的展示方式。比如保留幾個(gè)小數(shù)等。shadow:是否顯示陰影。textprops:文本的屬性(顏色,大小等)。 范例

plt.figure(figsize=(8,8),dpi=100,facecolor='white')
plt.pie(x = StockCode.values,                  #數(shù)據(jù)傳入
        radius=1.5,                            #半徑
        autopct='%.2f%%'                       #百分比顯示
        ,pctdistance=0.6,                      #百分比距離圓心比例
        labels=StockCode.index,                #標(biāo)簽
        labeldistance=1.1,                     #標(biāo)簽距離圓心比例
        wedgeprops ={'linewidth':1.5,'edgecolor':'green'}, #邊框的線寬和顏色
        textprops={'fontsize':10,'color':'blue'})  #文本字體大小和顏色
plt.title('商品銷量占比',pad=100)              #設(shè)置標(biāo)題及距離坐標(biāo)軸的位置
plt.show()

運(yùn)行結(jié)果:

6、箱線圖

箱圖的繪制方法是:

  •     :1、先找出一組數(shù)據(jù)的上限值、下限值、中位數(shù)(Q2)和下四分位數(shù)(Q1)以及上四分位數(shù)(Q3)
  •     :2、然后連接兩個(gè)四分位數(shù)畫(huà)出箱子
  •     :3、再將最大值和最小值與箱子相連接,中位數(shù)在箱子中間。  

中位數(shù):把數(shù)據(jù)按照從小到大的順序排序,然后最中間的那個(gè)值為中位數(shù),如果數(shù)據(jù)的個(gè)數(shù)為偶數(shù),那么就是最中間的兩個(gè)數(shù)的平均數(shù)為中位數(shù)。  
上下四分位數(shù):同樣把數(shù)據(jù)排好序后,把數(shù)據(jù)等分為4份。出現(xiàn)在`25%`位置的叫做下四分位數(shù),出現(xiàn)在`75%`位置上的數(shù)叫做上四分位數(shù)。但是四分位數(shù)位置的確定方法不是固定的,有幾種算法,每種方法得到的結(jié)果會(huì)有一定差異,但差異不會(huì)很大。

上下限的計(jì)算規(guī)則是:  

  • IQR=Q3-Q1  
  • 上限=Q3+1.5IQR  
  • 下限=Q1-1.5IQR

matplotlib中有plt.boxplot來(lái)繪制箱線圖,這個(gè)方法的相關(guān)參數(shù)如下:

x:需要繪制的箱線圖的數(shù)據(jù)。notch:是否展示置信區(qū)間,默認(rèn)是False。如果設(shè)置為True,那么就會(huì)在盒子上展示一個(gè)缺口。sym:代表異常點(diǎn)的符號(hào)表示,默認(rèn)是小圓點(diǎn)。vert:是否是垂直的,默認(rèn)是True,如果設(shè)置為False那么將水平方向展示。whis:上下限的系數(shù),默認(rèn)是1.5,也就是上限是Q3+1.5IQR,可以改成其他的。也可以為一個(gè)序列,如果是序列,那么序列中的兩個(gè)值分別代表的就是下限和上限的值,而不是再需要通過(guò)IQR來(lái)計(jì)算。positions:設(shè)置每個(gè)盒子的位置。widths:設(shè)置每個(gè)盒子的寬度。labels:每個(gè)盒子的label。meanlineshowmeans:如果這兩個(gè)都為True,那么將會(huì)繪制平均值的的線條。

范例:

#箱線圖 - 主要觀察數(shù)據(jù)是否有異常(離群點(diǎn))
#箱須-75%和25%的分位數(shù)+/-1.5倍分位差
plt.figure(figsize=(6.4,4.8),dpi=100)

#是否填充箱體顏色,是否展示均值,是否展示異常值,箱體設(shè)置,異常值設(shè)置,均值設(shè)置,中位數(shù)設(shè)置
plt.boxplot(x=UnitPrice                               #傳入數(shù)據(jù)
            ,patch_artist=True                                #是否填充箱體顏色
            ,showmeans=True                                   #是否展示均值
            ,showfliers=True                                  #是否展示異常值
            ,boxprops={'color':'black','facecolor':'white'}    #箱體設(shè)置
            ,flierprops={'marker':'o','markersize':4,'markerfacecolor':'red'} #異常值設(shè)置
            ,meanprops={'marker':'o','markersize':6,'markerfacecolor':'indianred'} #均值設(shè)置
            ,medianprops={'linestyle':'--','color':'blue'}   #中位數(shù)設(shè)置
           )
plt.show()

運(yùn)行結(jié)果:

7、雷達(dá)圖

雷達(dá)圖:又被叫做蜘蛛網(wǎng)圖,適用于顯示三個(gè)或更多的維度的變量的強(qiáng)弱情況

plt.polar來(lái)繪制雷達(dá)圖,x軸的坐標(biāo)點(diǎn)應(yīng)該為弧度(2*PI=360°)

范例:

import numpy as np
properties = ['輸出','KDA','發(fā)育','團(tuán)戰(zhàn)','生存']
values = [40,91,44,90,95,40]
theta = np.linspace(0,np.pi*2,6)
plt.polar(theta,values)
plt.xticks(theta,properties)
plt.fill(theta,values)

運(yùn)行結(jié)果:

注意事項(xiàng):

  • 因?yàn)?code>polar并不會(huì)完成線條的閉合繪制,所以我們?cè)诶L制的時(shí)候需要在theta中和values中在最后多重復(fù)添加第0個(gè)位置的值,然后在繪制的時(shí)候就可以和第1個(gè)點(diǎn)進(jìn)行閉合了。
  • polar只是繪制線條,所以如果想要把里面進(jìn)行顏色填充,那么需要調(diào)用fill函數(shù)來(lái)實(shí)現(xiàn)。
  • polar默認(rèn)的圓圈的坐標(biāo)是角度,如果我們想要改成文字顯示,那么可以通過(guò)xticks來(lái)設(shè)置。

到此這篇關(guān)于Python進(jìn)階Matplotlib庫(kù)圖繪制的文章就介紹到這了,更多相關(guān)Python Matplotlib庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論