matplotlib(直方圖,條形圖,餅圖,散點圖)基礎知識

import numpy as np

import pandas as pd

import matplotlib as mpl

import matplotlib.pyplot as plt

from pandas random import randn

from IPython.

%matplotlib inline

直方圖:

hist()的參數
bins
可以是一個bin數量的整數值,也可以是表示bin的一個序列。默認值爲10
range
bin的範圍,當bins參數爲序列時,此參數無效。範圍外的值將被忽略掉,默認值爲None
normed
如果值爲True,直方圖的值將進行歸一化處理,形成概率密度,默認值爲False
histtype
bar
默認爲bar類型的直方圖
barstacked
用於多種數據的堆疊直方圖
step
創建未填充的線形圖
stepfilled
創建默認填充的線形圖
align
用於bin邊界之間矩形條的居中設置。默認值爲mid,其他值爲left和right
color
指定直方圖的顏色。可以是單一顏色值或顏色的序列。如果指定了多個數據集合,顏色序列將會設置爲相同的順序。如果未指定,將會使用一個默認的線條顏色
orientation
通過設置orientation爲horizontal創建水平直方圖。默認值爲vertical

y=np.random.randn(1000)
x=np.arange(7)
ax=plt.gca()   #獲取當前列表
ax.hist(y) 
ax.set_xlim(-3,3)
ax.set_xlabel('X')
ax.set_ylabel('y')
ax.set_title('first test of hist')

總結:直方圖hist()內部只有一個參數y,用於顯示某一輸入數據的正態分佈圖

條形圖:

條形圖分爲bar(),barh():水平條形圖

plt.bar(left, height, width=0.8, bottom=None, hold=None, data=None, **kwargs)

left : sequence of scalars
    the x coordinates of the left sides of the bars    #設置爲X的值

height : sequence of scalars
    the heights of the bars    #相當於y的值

bottom : scalar or array-like, optional
    the y coordinate(s) of the bars
    default: None    

例題:

1:#繪製有誤差條的並列條形圖
data1=10*np.random.rand(5)
data2=10*np.random.rand(5)
data3=10*np.random.rand(5)
e2=0.5*np.abs(np.random.randn(len(data2)))
locs=np.arange(1,len(data1)+1)
width=0.27
plt.bar(locs,data1,width=width)
plt.bar(locs+width,data2,yerr=e2,width=width,color='g')
plt.bar(locs+2*width,data3,width=width,color='r')
plt.xticks(locs+width*1.5,locs)

plt.show()

2:水平條形圖

plt.barh([1,2,3],[3,2,5])  #水平條形圖先y後x
plt.show()

plt.barh(bottom, width, height=0.8, left=None, hold=None, **kwargs)

bottom : scalar or array-like
    the y coordinate(s) of the bars  標量或類似數組的y座標

width : scalar or array-like
    the width(s) of the bars  


條形圖總結:

1:條形圖內部參數plt.bar(x軸,y軸,寬度)

其中X軸,Y軸類型爲numpy.narray

2:水平條形圖內部參數([y軸列表],[X軸列表])    水平條形圖是先Y軸再由y軸來確定後面list的x座標

餅圖 :

餅圖 pie()  餅圖適合展示各部分佔總體的比例,
條形統計圖適合比較各部分的大小

plt.figure(figsize=(4,4))#將餅圖繪製在正方形區域內,用戶解決正方形內部的橢圓
x=[45,35,20]#當各部分之和大於1時,會自動計算各部分佔總體的百分比
labels=['cats','dogs','fishes']
plt.pie(x,labels=labels)  #labels參數可以設置各區域標籤
plt.show()


y=[0.1,0.2,0.3]

labels=['cats','dogs','fishes']

plt.pie(y,labels=labels)

plt.show()


3:繪製一個由多層次的餅圖

pie()參數:

1):X:餅圖中所有元素所佔的比例值或值(對於大於1會自動求其比例值)

2):labels:各個元素的標籤

3):labeldistance:參數設置標籤距離圓心的距離

4):autopct:參數比例值顯示格式

5):pctdistance:參數設置比例值距離圓心的距離

6):explode:參數設置每一塊距離圓心的距離

7):colors:參數設置每一塊的顏色

8):shadow:爲布爾值,是否設置陰影

9):startangle:指定圓弧開始繪製的角度

plt.figure(figsize=(4,4))

x=[4,9,21,55,30,18]
labels=['Swiss','Austria','spain','Italy','France','Benelux']
explode=[0.2,0.1,0,0,0.1,0]
colors=['r','k','b','m','c','g']

plt.pie(x,labels=labels,labeldistance=1.2,explode=explode,colors=colors,autopct='%1.1f%%',pctdistance=0.5,shadow=True)

plt.pie(x,labels=labels,labeldistance=1.2,explode=explode,colors=colors,autopct='%1.1f%%',pctdistance=0.5,shadow=True,startangle=67)

plt.show()





散點圖:

x = np.random.randn(1000)


y1 = np.random.randn(len(x))

y2 = 1.2 + np.exp(x)


ax1 = plt.subplot(121)

plt.scatter(x,y1,color='indigo',alpha=0.3,edgecolors='white',label = 'no correl')

plt.xlabel('no correlation')

plt.grid(True)

plt.legend()


ax2 = plt.subplot(122)

plt.scatter(x,y2,color='green',alpha = 0.3,edgecolors='gray',label=' strong correlation')

plt.xlabel(''correl)

plt.grid(True)

plt.legend()

plt.show()


2:帶有標記的線形圖例

plt.figure(figsize=(4,4))

plt.plot(randn(5).cumsum(),'k-',label='one',marker='o')

plt.plot(randn(5),cumsum(),'k--',label='two')

plt.show()


2)data = randn(10).cumcum()


plt.figure(figsize=(4,4))

plt.plot(data,'k-',label = 'Default')

plt.plot(data,'k--',drawstyle = 'steps-post',label = 'steps-post')

plt.legend()


set_xticks 和set_xticklabels來修改X軸刻度

ax=plot.subplot(111)

ticks = ax.set_xticks([0,250,500,750,1000])

labels = ax.set_xticklabels(['one','two','three','four','five'],rotation =30,fontsize = 'small')

#rotation=30 設置下標刻度偏移角度

ax.set_title('My first matplotlib plot')

ax.set_xlabel('stage')



同樣的設置y軸一樣的道理:

只是將刻度x改成y:set_yticks() 和set_yticklabels()


yticks =ax.set_yticks([-40,-20,0,20,40])

ylabel = ax.set_yticklabels([-40,-20,0,20,40],rotation = 30,fontsize ='small')


ax.ylabel('ystage')

將圖標保存爲SVG文件:

plt.savefig()

例如:plt.savefig('figpath.png',dpi = 400,bbox_inches = 'tight')  #得到一張帶有最小白邊,且分辨率爲400DPI的PNG圖片

dpi:“每英寸點數”分辨率

bbox_inches:可以剪除當前圖表周圍的空白部分。tight:表示嘗試剪除圖表周圍的空白部分。

通過文件擴展名,可以保存爲任何圖片形式

繪製圖形:

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(111)


rect = plt.Rectangle((0.2,0.75),0.4,0.15,color = 'k',alpha = 0.3)
circ = plt.Circle((0.7,0.2),0.2,color = 'b',alpha =0.3)
pgon = plt.Polygon([[0.15,0.2],[0.6,0.4],[0.7,0.2]],color ='y',alpha = 0.4)


ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)





發佈了39 篇原創文章 · 獲贊 16 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章