Python數據分析之matplotlib(提升篇)


散點圖(scatter)

fig,axes = plt.subplots(ncols=2,nrows=2)
ax1,ax2,ax3,ax4 = axes.ravel()
# example1
height=[161,170,182,175,173,165]
weight=[50,58,80,70,69,55]
ax1.scatter(height,weight) #繪製橫座標爲身高,縱座標爲體重散點圖

# example2
N = 1000
x = np.random.randn(N) #隨機生成一千個點
y = np.random.randn(N) #隨機生成一千個點
ax2.scatter(x,y) #繪製橫座標爲x,縱座標爲y散點圖

# example3

open,close=np.loadtxt('000001.csv',delimiter=',',skiprows=1,usecols=(1,4),unpack=True)
# loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
# fname:讀取文件的文件名。例如 '000001.csv'。
# dtype:數據類型。如float,str等。默認爲float
# comments 註釋
# delimiter:數據之間的分隔符。如使用逗號','。默認是空格
# skiprows跳過前幾行讀取,默認是0,必須是int整型。
# usecols:選取數據的列。
# unpack若是爲True,將分列讀取。

change=close-open
yesterday=change[:-1]
today=change[1:]
ax3.scatter(today,yesterday)

# example4
ax4.scatter(today,yesterday,s=50,c='r',marker='<',alpha=0.5)
# s:尺寸大小
# c: 顏色類型
# marker: 標記形狀
plt.show()

條形圖 (bar)

fig,axes = plt.subplots(ncols=2,nrows=2)
ax1,ax2,ax3,ax4 = axes.ravel()

N=5

y=[20,10,30,25,15]

index = np.arange(N)
# bar繪製條形圖
ax1.bar(left=index, height=y,width=0.3) #left:橫座標值 height:縱座標值 width:條形圖寬度
ax2.bar(left=index, height=y,color='red',width=0.3) # color:設置條形圖顏色
ax3.bar(left=0, bottom=index, width=y,height=0.5,orientation='horizontal')# orientation:'horizontal'設置爲橫向
ax4.barh(bottom=index,width=y,height=0.5) # barh 橫向條形圖
plt.show()
fig,axes = plt.subplots(ncols=2,nrows=2)
ax1,ax2,ax3,ax4 = axes.ravel()

index=np.arange(4)

sales_BJ=[52,55,63,53]
sales_SH=[44,66,55,41]
bar_width=0.3

ax1.bar(index,sales_BJ,bar_width,color='b')
ax1.bar(index+bar_width,sales_SH,bar_width,color='r') # index+bar_width實現橫向並排

ax2.bar(index,sales_BJ,bar_width,color='b')
ax2.bar(index,sales_SH,bar_width,color='r',bottom=sales_BJ) # bottom=sales_BJ實現縱向疊加

ax3.barh(bottom=index,width=sales_BJ,height=0.3,color='b')
ax3.barh(bottom=index+bar_width,width=sales_SH,height=0.3,color='r') # bottom=index+bar_width

ax4.barh(bottom=index,width=sales_BJ,height=0.3,color='b')
ax4.barh(bottom=index,width=sales_SH,height=0.3,color='r',left=sales_BJ) # left=sales_BJ

plt.show()

直方圖(hist)

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(212)

mu = 100
sigma = 20
x = mu +sigma * np.random.randn(2000)

ax1.hist(x,bins=10,color='green',normed=True) #輸入數據,bins=總共有幾條條狀圖,color=顏色,normed=True:縱座標總共爲1

ax2.hist(x,bins=50,color='red',normed=False) #normed=False:縱座標顯示實際值


x = np.random.randn(1000)+2
y = np.random.randn(1000)+3

ax3.hist2d(x,y,bins=10) #二維直方圖

plt.show()

餅狀圖(pie)

labels='frogs','hogs','dogs','logs'
sizes=15,20,45,10
colors='yellowgreen','gold','lightskyblue','lightcoral'
explode=0,0.1,0,0
plt.pie(sizes,explode=explode,labels=labels,colors=colors,labeldistance = 1.1 ,autopct='%3.1f%%',shadow=True,startangle=90,pctdistance = 0.6)
#labeldistance,文本的位置離遠點有多遠,1.1指1.1倍半徑的位置
#autopct,圓裏面的文本格式,%3.1f%%表示小數有三位,整數有一位的浮點數
#shadow,餅是否有陰影
#startangle,起始角度,0,表示從0開始逆時針轉,爲第一塊。通常選擇從90度開始比較好看
#pctdistance,百分比的text離圓心的距離
plt.axis('equal') #修正爲正圓 設置x,y軸刻度一致,這樣餅圖才能是圓的
plt.show()

箱型圖(boxplot)

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

np.random.seed(100)

data = np.random.normal(size=1000, loc=0.0, scale=1.0)

ax1.boxplot(data,sym='o',whis=1.5)
# plt.boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None)
# x:指定要繪製箱線圖的數據;
# notch:是不是凹口的形式展示箱線圖,默認非凹口;
# sym:指定異常點的形狀,默認爲+號顯示;
# vert:是否須要將箱線圖垂直襬放,默認垂直襬放;
# whis:指定上下須與上下四分位的距離,默認爲1.5倍的四分位差;
# positions:指定箱線圖的位置,默認爲[0,1,2…];
# widths:指定箱線圖的寬度,默認爲0.5;
# patch_artist:是否填充箱體的顏色;
# meanline:是否用線的形式表示均值,默認用點來表示;
# showmeans:是否顯示均值,默認不顯示;
# showcaps:是否顯示箱線圖頂端和末端的兩條線,默認顯示;
# showbox:是否顯示箱線圖的箱體,默認顯示;
# showfliers:是否顯示異常值,默認顯示;
# boxprops:設置箱體的屬性,如邊框色,填充色等;
# labels:爲箱線圖添加標籤,相似於圖例的做用;
# filerprops:設置異常值的屬性,如異常點的形狀、大小、填充色等;
# medianprops:設置中位數的屬性,如線的類型、粗細等;
# meanprops:設置均值的屬性,如點的大小、顏色等;
# capprops:設置箱線圖頂端和末端線條的屬性,如顏色、粗細等;
# whiskerprops:設置須的屬性,如顏色、粗細、線的類型等;
data = np.random.normal(size=(100, 4), loc=0.0, scale=1.0)

labels = ['A','B','C','D']

ax2.boxplot(data, labels=labels)

plt.show()

顏色與樣式

顏色

樣式

  • 線條樣式html

  • 標記樣式web

fig = plt.figure()
ax1 = fig.add_subplot(321)
ax2 = fig.add_subplot(322)
ax3 = fig.add_subplot(323)
ax4 = fig.add_subplot(324)
ax5 = fig.add_subplot(313)

#內建默認顏色
y=np.arange(1,5)
ax1.plot(y)


#灰色陰影,html,RGB
y=np.arange(1,5)
ax2.plot(y,'y')   #內建默認顏色
ax2.plot(y+1,color=(0.1,0.2,0.3)) #RGB
ax2.plot(y+2,'#FF00FF')  #html
ax2.plot(y+3,color='0.5') #灰色陰影


#線條樣式
y=np.arange(1,5)
ax3.plot(y,'--'); # 線條
ax3.plot(y+1,'-.'); # 點線
ax3.plot(y+2,':'); # 點

#點樣式,是否加線條取決於marker
y=np.arange(1,5)
ax4.plot(y,marker='o');
ax4.plot(y+1,marker='D');
ax4.plot(y+2,marker='^');
ax4.plot(y+3,'s');
ax4.plot(y+4,'p');
ax4.plot(y+5,'x');


#樣式字符串,同時表示顏色,點型,線性(重要!!)
y=np.arange(1,5)
ax5.plot(y,'cx--');
ax5.plot(y+1,'kp:');
ax5.plot(y+2,'mo-.');

plt.show()

網格(grid)

y = np.arange(1,5,0.1)
plt.plot(y,y**2)
plt.grid(True,color='r',linestyle='--',linewidth='2')
# True 顯示網格
# color 設置網格的顏色
# linestyle 設置線顯示的類型(一共四種)
# linewidth 設置網格的寬度
plt.show()

x= np.arange(1,10,0.1)
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.grid()
ax1.plot(x,np.log(x))
plt.show()

圖例(legend)

x = np.arange(1,11,1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,x*2,label='Normal')
ax.plot(x,x*3,label='Fast')
ax.plot(x,x*4,label='Faster')
ax.plot(x,x*5,label='cool')
ax.plot(x,x*6,label='Best')
plt.legend(loc=0)
# loc= 0-10
# 0: ‘best'
# 1: ‘upper right'
# 2: ‘upper left'
# 3: ‘lower left'
# 4: ‘lower right'
# 5: ‘right'
# 6: ‘center left'
# 7: ‘center right'
# 8: ‘lower center'
# 9: ‘upper center'
# 10: ‘cente ’
# 參考 http://blog.csdn.net/helunqu2017/article/details/78641290
plt.show()

座標軸範圍調整

#ax.axis([0,10,0,100]) [x左,x右,y下,y上]
x = np.arange(-10,10,0.1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,x**2)
ax.axis([0,10,0,100])

#plt.xlim([-5,5]) ,調整x軸座標範圍
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,x**2)
plt.xlim([-5,5])
#至關於 plt.xlim(xmin=-5,xmax=5)

#plt.ylim([0,60]) ,調整y軸座標範圍
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(x,x**2)
plt.ylim([0,60])
#至關於 plt.ylim(ymin=0,ymax=60)

plt.show()

座標軸刻度調整

x = np.arange(0,11,0.1)

fig1 = plt.figure()
ax1  = fig1.add_subplot(111)
ax1.plot(x,x)
#ax1.locator_params(nbins=20) #同時調整x軸與y軸
#ax1.locator_params('x',nbins=20) #只調整x軸
ax1.locator_params('y',nbins=20) #只調整y軸
plt.axis([0,10,0,10])


#日期的相關調整
start = datetime.datetime(2015,1,1)
stop  = datetime.datetime(2016,1,1)
delta = datetime.timedelta(days=1)

dates = mpl.dates.drange(start,stop,delta)
y = np.random.rand(len(dates))

fig2 = plt.figure()
ax2  = fig2.add_subplot(111)
ax2.plot_date(dates,y,linestyle='-',marker='')

#日期格式調整,不重疊
date_format= mpl.dates.DateFormatter('%Y-%m')
ax2.xaxis.set_major_formatter(date_format)
fig2.autofmt_xdate()#防止重疊

plt.show()

圖中添加新座標軸

x = np.arange(1,11,0.1)
y1 = x*x
y2 = np.log(x)

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax2 = ax1.twinx()

#ax1.set_ylable('Y1')
#ax2.set_ylable('Y2')

ax1.plot(x,y1)
ax2.plot(x,y2,'--r')

plt.show()

圖中畫註釋符號

x =np.arange(-10,11,1)
y = x*x

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,y)
ax1.annotate('this is bottom',xy=(0,0),xytext=(-1.25,20),
            arrowprops=dict(facecolor='r',frac=0.2))
# annotate(s, xy, xytext=None, xycoords='data',textcoords='data'arrowprops=None, **kwargs)
# s : 描述的內容
# xy : 加描述的點
# xytext : 標註的位置,xytext=(30,-30),表示從標註點x軸方向上增長30,y軸方減30的位置
# xycoords 、textcoords :這兩個參數試了好屢次沒弄明白,只知道 xycoords='dat給定就行,
# textcoords='offset points' 標註的內容從xy設置的點進行偏移xytext
# textcoords='data' 標註內容爲xytext的絕對座標  
# fontsize : 字體大小,這個沒什麼好說的
# arrowstyle : 箭頭樣式'->'指向標註點 '<-'指向標註內容 還有不少'-'
              # '->'   head_length=0.4,head_width=0.2
              # '-['  widthB=1.0,lengthB=0.2,angleB=None
              # '|-|'     widthA=1.0,widthB=1.0
              # '-|>'  head_length=0.4,head_width=0.2
              # '<-'   head_length=0.4,head_width=0.2
              # '<->'   head_length=0.4,head_width=0.2
              # '<|-'  head_length=0.4,head_width=0.2
              # '<|-|>'     head_length=0.4,head_width=0.2
              # 'fancy'   head_length=0.4,head_width=0.4,tail_width=0.4
              # 'simple'  head_length=0.5,head_width=0.5,tail_width=0.2
              # 'wedge'   tail_width=0.3,shrink_factor=0.5
plt.show()

圖形中純文字標註

x =np.arange(-10,11,1)
y = x*x

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,y)
ax1.text(-3,40,'function:y=x*x',family='fantasy',size=15,color='g',style='oblique',weight=20,bbox=dict(facecolor='r',alpha=0.2))
ax1.text(-3,30,'function:y=x*x',family='serif',size=15,color='r',style='italic',weight='black')

plt.show()

圖像中畫數學公式

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.set_xlim([1,7])
ax1.set_ylim([1,5])
ax1.text(2,4,r"$ \alpha_i \beta_j \pi \lambda \omega $",size=15)
ax1.text(4,4,r"$ \sin(0)=\cos(\frac{\pi}{2}) $",size=15)
ax1.text(2,2,r"$ \lim_{x \rightarrow y} \frac{1}{x^3} $",size=15)
ax1.text(4,2,r"$ \sqrt[4]{x}=\sqrt{y}$",size=15)
plt.show()

填充上色

x = np.linspace(0,5*np.pi,1000)
y1 = np.sin(x)
y2 = np.sin(2*x)

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

# ax1.fill(x,y1,'g',alpha=0.2)
# ax1.fill(x,y2,'r',alpha=0.2)
ax1.fill_between(x,y1,y2,where=y1>y2,facecolor='y')
ax1.fill_between(x,y1,y2,where=y1<y2,facecolor='b')
ax1.grid()

plt.show()

畫填充好的圖形

import matplotlib.patches as mpatches
fig,ax = plt.subplots()

xy1 = np.array([0.2,0.2])
xy2 = np.array([0.2,0.8])
xy3 = np.array([0.8,0.2])
xy4 = np.array([0.8,0.8])

circle = mpatches.Circle(xy1,0.05) #xy1 圓心
rect = mpatches.Rectangle(xy2,0.2,0.1,color='r') #xy2 左下角對應的點
polygen = mpatches.RegularPolygon(xy3,5,0.1,color='g') #xy3 圓心
ellipse = mpatches.Ellipse(xy4,0.4,0.2,color='y')

ax.add_patch(circle)
ax.add_patch(rect)
ax.add_patch(polygen)
ax.add_patch(ellipse)

plt.axis('equal')
plt.grid()
plt.show()

參考

matplotlib核心剖析(http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html#commentform)微信

本文分享自微信公衆號 - AI異構(gh_ed66a0ffe20a)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。app

相關文章
相關標籤/搜索