matplotlib圖表介紹

Matplotlib 是一個python 的繪圖庫,主要用于生成2D圖表。

常用到的是matplotlib中的pyplot,導入方式import matplotlib.pyplot as plt

一、顯示圖表的模式

1.plt.show()

該方式每次都需要手動show()才能顯示圖表,由于pycharm不支持魔法函數,因此在pycharm中都需要采取這種show()的方式。

arr = np.random.rand(10)
plt.plot(arr)
plt.show()  #每次都需要手動show()

?

2.魔法函數%matplotlib inline

魔法函數不需要手動show(),可直接生成圖表,但是魔法函數無法在pycharm中使用,下面都是在jupyter notebook中演示。

inline方式直接在代碼的下方生成一個圖表。

%matplotlib inline   
x = np.random.rand(1000)
y = np.random.rand(1000)
plt.scatter(x,y)   #最基本散點圖
# <matplotlib.collections.PathCollection at 0x54b2048>

?

?3.魔法函數%matplotlib notebook

%matplotlib notebook
s = pd.Series(np.random.rand(100))
s.plot(style = 'k--o',figsize = (10,5))

notebook方式,代碼需要運行兩次,會在代碼下方生成一個可交互的圖表,可對圖表進行放大、拖動、返回原樣等操作。?

?

4.魔法函數%matplotlib qt5

%matplotlib qt5
plt.gcf().clear()
df = pd.DataFrame(np.random.rand(50,2),columns=['A','B'])
df.hist(figsize=(12,5),color='g',alpha=0.8)

qt5方式會彈出一個獨立于界面上的可交互圖表。

由于可交互的圖表比較占內存,運行起來稍顯卡,因此常采用inline方式。

二、生成圖表的方式

1.Seris生成

ts = pd.Series(np.random.randn(50),index=pd.date_range('2019/1/1/',periods=50))
ts = ts.cumsum()
ts.plot()

?

2.DataFrame生成

df = pd.DataFrame(np.random.rand(20,3),columns=['A','B','C'])
df.plot()

?

三、圖表的基本元素

plot的使用方法,以下圖表都在%matplotlib inline 模式下生成。

plot(kind='line',ax=None,figsize=None,use_index=True,title=None,grid=None,legend=None,\style=None,logx=False,logy=False,loglog=False,xticks=None,yticks=None,xlim=None,\ylim=None,rot=None,fontsize=None,colormpap=None,subplots=False,table=False,xerr=None,yerr=None,\lable=None,secondary_y=False,**kwargs)
# kind:圖表類型,默認為line折線圖,其他bar直方圖、barh橫向直方圖
# ax:第幾個子圖
# figsize:圖表大小,即長和寬,默認為None,指定形式為(m,n)
# use_index:是否以原數據的索引作為x軸的刻度標簽,默認為True,如果設置為False則x軸刻度標簽為從0開始的整數
# title:圖表標題,默認為None
# grid:是否顯示網格,默認為None,也可以直接使用plt.grid()
# legend:如果圖表包含多個序列,序列的注釋的位置
# style:風格字符串,包含了linestyle、color、marker,默認為None,如果單獨指定了color以color的顏色為準
# color:顏色,默認為None
# xlim和ylim:x軸和y軸邊界
# xticks和yticks:x軸和y軸刻度標簽
# rot:x軸刻度標簽的逆時針旋轉角度,默認為None,例如rot = 45表示x軸刻度標簽逆時針旋轉45°
# fontsize:x軸和y軸刻度標簽的字體大小
# colormap:如果一個圖表上顯示多列的數據,選擇顏色族以區分不同的列
# subplots:是否分子圖顯示,默認為None,如果一個圖標上顯示多列的數據,是否將不同的列拆分到不同的子圖上顯示
# label:圖例標簽,默認為None,DataFrame格式以列名為label
# alpha:透明度
plot()使用方法

?

圖表名稱,x軸和y軸的名稱、邊界、刻度、標簽等屬性。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(10,2),columns=['A','B'])
fig = df.plot(figsize=(6,4)) #figsize表示圖表大小,即長和寬
plt.title('test')   #圖表名稱
plt.xlabel('x-axis')  #x軸名稱
plt.ylabel('y-axis')  #y軸名稱
plt.legend(loc=0)  #圖表位置
plt.xlim([0,10])  #x軸邊界
plt.ylim([0,1])   #y軸邊界
plt.xticks(range(1,10))  #x軸刻度間隔
plt.yticks([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])  #y軸刻度間隔
fig.set_xticklabels('%d'%i for i in range(1,10))  #x軸顯示標簽,設置顯示整數
fig.set_yticklabels('%.2f'%i for i in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])  #y軸顯示標簽,設置顯示2位小數# legend的loc,位置
# 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:center

?

是否顯示網格及網格屬性、是否顯示坐標軸、刻度方向等。

x = np.linspace(-np.pi,np.pi,500)
c,s = np.cos(x),np.sin(x)
plt.plot(x,c)
plt.plot(x,s)
plt.grid(linestyle = '--',color = 'gray',linewidth = '0.5',axis = 'both')  #plt.grid()表示顯示網格,參數分別表示網格線型、顏色、寬度、顯示軸(x,y,both表示顯示x軸和y軸)
plt.tick_params(bottom='on',top='off',left='on',right='off')   #是否顯示刻度,默認left和bottom顯示import matplotlib
matplotlib.rcParams['xtick.direction']='in'  
matplotlib.rcParams['ytick.direction']='in'  #刻度的顯示方向,默認為out,in表示向內,out表示向外,inout表示穿透坐標軸內外都有

frame = plt.gca()
# plt.axis('off')   #關閉坐標軸
# frame.axes.get_xaxis().set_visible(False)  #x軸不可見
# frame.axes.get_yaxis().set_visible(False)  #y軸不可見

linestyle:線型-:實線,默認--:虛線-.:一個實線一個點::點
linestyle線型

?

marker:值在x刻度上的顯示方式'.'       point marker','       pixel marker'o'       circle marker'v'       triangle_down marker'^'       triangle_up marker'<'       triangle_left marker'>'       triangle_right marker'1'       tri_down marker'2'       tri_up marker'3'       tri_left marker'4'       tri_right marker's'       square marker'p'       pentagon marker'*'       star marker'h'       hexagon1 marker'H'       hexagon2 marker'+'       plus marker'x'       x marker'D'       diamond marker'd'       thin_diamond marker'|'       vline marker'_'       hline marker
markerx刻度上值的顯示方式

?

color:顏色r:red紅色y:yello黃色        g:green綠色b:blue藍色k:black黑色
alpha:透明度,0-1之間colormap:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r
color顏色

?

?

也可在創建圖表時通過style='線型顏色顯示方式'

例如style = '-ro'表示設置線條為實現、顏色為紅色,marker為實心圓

?

使用python內置的風格樣式style,需導入另外一個模塊import matplotlib.style as psl

import matplotlib.style as psl
print(psl.available)
psl.use('seaborn')
plt.plot(pd.DataFrame(np.random.rand(20,2),columns=['one','two']))

?

?設置主刻度、此刻度、刻度標簽顯示格式等

from matplotlib.ticker import MultipleLocator,FormatStrFormatter
t = np.arange(0,100)
s = np.sin(0.1*np.pi*t)*np.exp(-0.01*t)
ax = plt.subplot()  #不直接在plot中設置刻度
plt.plot(t,s,'-go')
plt.grid(linestyle='--',color='gray',axis='both')xmajorLocator = MultipleLocator(10)  #將x主刻度標簽設置為10的倍數
xmajorFormatter = FormatStrFormatter('%d')  #x主刻度的標簽顯示為整數
xminorLocator = MultipleLocator(5) #將x次刻度標簽設置為5的倍數
ax.xaxis.set_major_locator(xmajorLocator) #設置x軸主刻度
ax.xaxis.set_major_formatter(xmajorFormatter)  #設置x軸主刻度標簽的顯示格式
ax.xaxis.set_minor_locator(xminorLocator)  #設置x軸次刻度
ax.xaxis.grid(which='minor')  #設置x軸網格使用次刻度

ymajorLocator = MultipleLocator(0.5)  
ymajorFormatter = FormatStrFormatter('%.2f')
yminorLocator = MultipleLocator(0.25) 
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)
ax.yaxis.set_minor_locator(yminorLocator)
ax.yaxis.grid(which='minor')# ax.xaxis.set_major_locator(plt.NullLocator)  #刪除x軸的主刻度
# ax.xaxis.set_major_formatter(plt.NullFormatter)   #刪除x軸的標簽格式
# ax.yaxis.set_major_locator(plt.NullLocator)
# ax.yaxis.set_major_formatter(plt.NullFormatter)

?

?

注釋和圖表保存

注釋:plt.text(x軸值,y軸值,'注釋內容')

水平線:plt.axhline(x值)

數值線:plt.axvline(y值)

刻度調整:plt.axis('equal')設置x軸和y軸每個單位表示的刻度相等

子圖位置調整:plt.subplots_adjust(left=None, bottom=None, right=None, top=None,wspace=None, hspace=None),子圖距離畫板上下左右的距離,子圖之間的寬度和高度

保存:plt.savefig(保存路徑及文件名稱,dpi=n,bbox_inches='tight',facecolor='red',edgecolor='yellow')

   dpi表示分辨率,值越大圖片越清晰;bbox_inches為tight表示嘗試剪去圖表周圍空白部分,facecolor為圖表背景色,默認為白色,edgecolor為邊框顏色,默認為白色。

df = pd.DataFrame({'A':[1,3,2,6,5,8,5,9],'B':[7,2,6,4,8,5,4,3]})
df.plot()
plt.text(2,6,'^_^',fontsize='12')
plt.savefig(r'C:\Users\penghuanhuan\Desktop\haha.png',dpi=400,bbox_inches='tight',facecolor='red',edgecolor='yellow')
print('finished')

?

四、圖表各對象

figure相當于一塊畫板,ax是畫板中的圖表,一個figure畫板中可以有多個圖表。

創建figure對象:

plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=Figure, clear=False, **kwargs )

如果不設置figure對象,在調用plot時會自動生成一個并且生成其中的一個子圖,且所有plot生成的圖表都顯示在一個圖表上面。

num:指定為畫板中的第幾個圖表,在同一段代碼中,相同figure對象的不同num,各自生成一個圖表,相同figure對象的相同num和不同figure對象的相同num,均生成在一個圖標上。

figsize:圖表的大小,即長和寬,元組形式(m,n)

dpi:分辨率

?

1.創建子圖方法1

①通過plt生成figure對象

②通過figure對象的add_subplot(m,n,p)創建子圖,表示生成m*n個子圖,并選擇第p個子圖,子圖的順序由左到右由上到下

③在子圖上繪制圖表

#子圖
fig = plt.figure(figsize = (8,4),facecolor = 'lightgray')  #創建figure對象

ax1 = fig.add_subplot(2,2,1)  #創建一個2*2即4個子圖,并選擇第1個子圖,參數也可以直接寫成221# ax1 =plt.subplot(2,2,1) 也可以使用這種方式添加子圖
plt.plot(np.random.rand(20),'k--')  #在子圖上1繪制圖表
plt.plot(np.random.rand(20),'b--')  #在子圖上1繪制圖表
# ax1.plot(np.random.rand(20),'b--')

ax2 = fig.add_subplot(2,2,3)  #選擇第3個子圖
ax2.scatter(np.random.rand(100),np.random.rand(100))  #在子圖上3繪制圖表

ax3 = fig.add_subplot(2,2,2)   #選擇第2個子圖
ax3.hist(np.random.rand(20))ax4 = fig.add_subplot(2,2,4)  #選擇第4個子圖
ax4.plot(pd.DataFrame(np.random.rand(10,2),columns = ['A','B']))
通過figure對象添加子圖

?

?

2.創建子圖方法2

①通過plt的subplots(m,n)方法生成一個figure對象和一個表示figure對象m*n個子圖的二維數組

②通過二維數組選擇子圖并在子圖上繪制圖表

fig,axes = plt.subplots(2,3,figsize = (10,6))  #生成一個figure對象,和一個2*3的二維數組,數組元素為子圖對象
#subplots方法還有參數sharex和sharey,表示是否共享x軸和y軸,默認為False
print(fig,type(fig)) #figure對象
print(axes,type(axes))ax1 = axes[0][1]  #表示選擇第1行第2個子圖
ax1.plot(np.random.rand(20))ax2 = axes[1,0]  #表示選擇第2行第1個子圖
ax2.plot(np.arange(10))plt.subplots_adjust(wspace=0.2,hspace=0.3) #調整子圖之間的間隔寬、間隔高占比
通過subplots添加子圖

?

3.子圖的創建方法3

在創建plot的時候添加參數subplot=True即可

df.plot(style='--ro',subplots=True,figsize=(10,8),layout=(2,2),sharex=False,sharey=True)

subplots:默認為False,在一張圖表上顯示,True則會拆分為子圖

layout:子圖的排列方式,即幾行幾列

sharex:默認為True

sharey:默認為False

df = pd.DataFrame(np.random.rand(100,4))
df.plot(style='--ro')
df.plot(style='--ro',subplots=True,figsize=(10,8),layout=(2,2),sharex=False,sharey=True)

?

?

?

顯示漢字問題請參考https://www.cnblogs.com/kuxingseng95/p/10021788.html

轉載于:https://www.cnblogs.com/Forever77/p/11299813.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391891.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391891.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391891.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

到2025年將保持不變的熱門流行技術

重點 (Top highlight)I spent a good amount of time interviewing SMEs, data scientists, business analysts, leads & their customers, programmers, data enthusiasts and experts from various domains across the globe to identify & put together a list that…

spring—SpringMVC的請求和響應

SpringMVC的數據響應-數據響應方式 頁面跳轉 直接返回字符串 RequestMapping(value {"/qq"},method {RequestMethod.GET},params {"name"})public String method(){System.out.println("controller");return "success";}<bea…

Maven+eclipse快速入門

1.eclipse下載 在無外網情況下&#xff0c;無法通過eclipse自帶的help-install new software輸入url來獲取maven插件&#xff0c;因此可以用集成了maven插件的免安裝eclipse(百度一下有很多)。 2.jdk下載以及環境變量配置 JDK是向前兼容的&#xff0c;可在Eclipse上選擇編譯器版…

源碼閱讀中的收獲

最近在做短視頻相關的模塊&#xff0c;于是在看 GPUImage 的源碼。其實有一定了解的伙伴一定知道 GPUImage 是通過 addTarget 鏈條的形式添加每一個環節。在對于這樣的設計贊嘆之余&#xff0c;想到了實際開發場景下可以用到的場景&#xff0c;借此分享。 我們的項目中應該有很…

馬爾科夫鏈蒙特卡洛_蒙特卡洛·馬可夫鏈

馬爾科夫鏈蒙特卡洛A Monte Carlo Markov Chain (MCMC) is a model describing a sequence of possible events where the probability of each event depends only on the state attained in the previous event. MCMC have a wide array of applications, the most common of…

PAT乙級1012

題目鏈接 https://pintia.cn/problem-sets/994805260223102976/problems/994805311146147840 題解 就比較簡單&#xff0c;判斷每個數字是哪種情況&#xff0c;然后進行相應的計算即可。 下面的代碼中其實數組是不必要的&#xff0c;每取一個數字就可以直接進行相應計算。 // P…

我如何在昌迪加爾大學中心組織Google Hash Code 2019

by Neeraj Negi由Neeraj Negi 我如何在昌迪加爾大學中心組織Google Hash Code 2019 (How I organized Google Hash Code 2019 at Chandigarh University Hub) This is me !!! Neeraj Negi — Google HashCode Organizer這就是我 &#xff01;&#xff01;&#xff01; Neeraj …

leetcode 665. 非遞減數列(貪心算法)

給你一個長度為 n 的整數數組&#xff0c;請你判斷在 最多 改變 1 個元素的情況下&#xff0c;該數組能否變成一個非遞減數列。 我們是這樣定義一個非遞減數列的&#xff1a; 對于數組中所有的 i (0 < i < n-2)&#xff0c;總滿足 nums[i] < nums[i 1]。 示例 1: …

django基于存儲在前端的token用戶認證

一.前提 首先是這個代碼基于前后端分離的API,我們用了django的framework模塊,幫助我們快速的編寫restful規則的接口 前端token原理: 把(token加密后的字符串,keyname)在登入后發到客戶端,以后客戶端再發請求,會攜帶過來服務端截取(token加密后的字符串,keyname),我們再利用解密…

數據分布策略_有效數據項目的三種策略

數據分布策略Many data science projects do not go into production, why is that? There is no doubt in my mind that data science is an efficient tool with impressive performances. However, a successful data project is also about effectiveness: doing the righ…

cell 各自的高度不同的時候

1, cell 根據文字、圖片等內容&#xff0c;確定自己的高度。每一個cell有自己的高度。 2&#xff0c;tableView 初始化 現實的時候&#xff0c;不是從第一個cell開始顯示&#xff0c;&#xff08;從第二個&#xff1f;&#xff09;&#xff0c;非非正常顯示。 a:cell 的高度問題…

leetcode 978. 最長湍流子數組(滑動窗口)

當 A 的子數組 A[i], A[i1], …, A[j] 滿足下列條件時&#xff0c;我們稱其為湍流子數組&#xff1a; 若 i < k < j&#xff0c;當 k 為奇數時&#xff0c; A[k] > A[k1]&#xff0c;且當 k 為偶數時&#xff0c;A[k] < A[k1]&#xff1b; 或 若 i < k < j&…

spring boot源碼下載地址

github下載&#xff1a; https://github.com/spring-projects/spring-boot/tree/1.5.x git地址&#xff1a; https://github.com/spring-projects/spring-boot.git 因為項目中目前使用的就是spring boot 1.5.19版本&#xff0c;因此這里先研究spring boot 1.5版本源碼.轉載于:h…

java基礎學習——5、HashMap實現原理

一、HashMap的數據結構 數組的特點是&#xff1a;尋址容易&#xff0c;插入和刪除困難&#xff1b;而鏈表的特點是&#xff1a;尋址困難&#xff0c;插入和刪除容易。那么我們能不能綜合兩者的特性&#xff0c;做出一種尋址容易&#xff0c;插入刪除也容易的數據結構&#xff1…

看懂nfl定理需要什么知識_NFL球隊為什么不經常通過?

看懂nfl定理需要什么知識Debunking common NFL myths in an analytical study on the true value of passing the ball在關于傳球真實價值的分析研究中揭穿NFL常見神話 Background背景 Analytics are not used enough in the NFL. In a league with an abundance of money, i…

Docker初學者指南-如何創建您的第一個Docker應用程序

您是一名開發人員&#xff0c;并且想要開始使用Docker&#xff1f; 本文是為您準備的。 (You are a developer and you want to start with Docker? This article is made for you.) After a short introduction on what Docker is and why to use it, you will be able to cr…

mybatis if-else(寫法)

mybaits 中沒有else要用chose when otherwise 代替 范例一 <!--批量插入用戶--> <insert id"insertBusinessUserList" parameterType"java.util.List">insert into business_user (id , user_type , user_login )values<foreach collection…

spring—攔截器和異常

SpringMVC的攔截器 SpringMVC攔截器-攔截器的作用 Spring MVC 的攔截器類似于 Servlet 開發中的過濾器 Filter&#xff0c;用于對處理器進行預處理和后處理。 將攔截器按一定的順序聯結成一條鏈&#xff0c;這條鏈稱為攔截器鏈&#xff08;InterceptorChain&#xff09;。在…

29/07/2010 sunrise

** .. We can only appreciate the miracle of a sunrise if we have waited in the darkness .. 人們在黑暗中等待著&#xff0c;那是期盼著如同日出般的神跡出現 .. 附&#xff1a;27/07/2010 sunrise ** --- 31 July 改動轉載于:https://www.cnblogs.com/orderedchaos/archi…

密度聚類dbscan_DBSCAN —基于密度的聚類方法的演練

密度聚類dbscanThe idea of having newer algorithms come into the picture doesn’t make the older ones ‘completely redundant’. British statistician, George E. P. Box had once quoted that, “All models are wrong, but some are useful”, meaning that no model…