Python matplotlib實(shí)用繪圖技巧匯總
前言
在日常的業(yè)務(wù)數(shù)據(jù)分析 ,可視化是非常重要的步驟。這里總結(jié)了matplotlib常用繪圖技巧,希望可以幫助大家更加更加高效的、美觀的顯示圖表。作者:北山啦

Matplotlib 是 Python 的繪圖庫(kù)。 它可與 NumPy 一起使用,提供了一種有效的 MatLab 開(kāi)源替代方案。 它也可以和圖形工具包一起使用,如 PyQt 和wxPython。
pip3 install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
import matplotlib.pyplot as plt
顯示中文
借助全局參數(shù)配置字典rcParams,只需要在代碼開(kāi)頭,添加如下兩行代碼即可
plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False
同時(shí)還可以設(shè)置字體,常見(jiàn)字體:
font.family 字體的名稱(chēng)
sans-serif 西文字體(默認(rèn))
SimHei 中文黑體
FangSong 中文仿宋
YouYuan 中文幼圓
STSong 華文宋體
Kaiti 中文楷體
LiSu 中文隸書(shū)
字體風(fēng)格
plt.rcParams["font.style"] = "italic"
繪制子圖
plt.subplot2grid()
plt.subplot2grid((3,3),(0,0),colspan=3) """""" plt.subplot2grid((3,3),(1,0),colspan=2) """""" plt.subplot2grid((3,3),(1,2),rowspan=2) """""" plt.subplot2grid((3,3),(2,0)) """""" plt.subplot2grid((3,3),(2,1)) plt.show()

2. plt.subplot()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 畫(huà)第1個(gè)圖:折線圖
x=np.arange(1,100)
plt.subplot(221)
plt.plot(x,x*x)
# 畫(huà)第2個(gè)圖:散點(diǎn)圖
plt.subplot(222)
plt.scatter(np.arange(0,10), np.random.rand(10))
# 畫(huà)第3個(gè)圖:餅圖
plt.subplot(223)
plt.pie(x=[15,30,45,10],labels=list('ABCD'),autopct='%.0f',explode=[0,0.05,0,0])
# 畫(huà)第4個(gè)圖:條形圖
plt.subplot(224)
plt.bar([20,10,30,25,15],[25,15,35,30,20],color='b')
plt.show()

matplotlib繪圖設(shè)置不顯示邊框、坐標(biāo)軸
對(duì)于有些圖形我們希望通過(guò)隱藏坐標(biāo)軸來(lái)顯得更加美觀
plt.xticks([]) plt.yticks([]) ax = plt.subplot(2,5,1) # 去除黑框 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False)
實(shí)例:
#author:https://beishan.blog.csdn.net/
import matplotlib.pyplot as plt
for i in range(0,10):
fig = plt.gcf()
fig.set_size_inches(12,6)
ax = plt.subplot(2,5,i+1)
# 去除坐標(biāo)軸
plt.xticks([])
plt.yticks([])
# 去除黑框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
# 設(shè)置各個(gè)子圖間間距
plt.subplots_adjust(left=0.10, top=0.88, right=0.65, bottom=0.08, wspace=0.02, hspace=0.02)
ax.imshow(Xtrain[i],cmap="binary")

提高分辨率
如果感覺(jué)默認(rèn)生成的圖形分辨率不夠高,可以嘗試修改 dpi 來(lái)提高分辨率
plt.figure(figsize = (7,6),dpi =100)
設(shè)置繪圖風(fēng)格
有時(shí)我們會(huì)覺(jué)得matplotlib默認(rèn)制作出來(lái)的圖片太樸素了,不夠高級(jí),其實(shí)開(kāi)發(fā)者也內(nèi)置了幾十種主題讓我們自己選擇,只要使用plt.style.use(‘主題名')指定主題即可
plt.style.use('ggplot')
常用的樣式有
Solarize_Light2
_classic_test_patch
bmh
classic
dark_background
fast
fivethirtyeight
ggplot
grayscale
seaborn
seaborn-bright
seaborn-colorblind
seaborn-dark
seaborn-dark-palette
seaborn-darkgrid
seaborn-deep
seaborn-muted
seaborn-notebook
seaborn-paper
seaborn-pastel
seaborn-poster
seaborn-talk
seaborn-ticks
seaborn-white
seaborn-whitegrid
tableau-colorblind10
添加標(biāo)題
plt.title("2020-2021北山啦粉絲數(shù)增長(zhǎng)圖")
顯示網(wǎng)格
plt.grid() plt.grid(color='g',linewidth='1',linestyle='-.')
圖例設(shè)置
plt.legend(["2020","2021"],loc="best")
也可以給圖例添加標(biāo)題
plt.plot([1,3,5,7],[4,9,6,8],"ro--")
plt.plot([1,2,3,4], [2,4,6,8],"gs-.")
plt.legend(["2020","2021"],loc="best",title="標(biāo)題")
plt.title("2020-2021北山啦粉絲數(shù)增長(zhǎng)圖")
添加公式
有時(shí)我們?cè)诶L圖時(shí)需要添加帶有數(shù)學(xué)符號(hào)、公式的文字,
plt.text(11000,0.45,r'擬合曲線為$f(x) = x^2-4x+0.5$')
圖形交互設(shè)置
jupyter中的魔法方法
%matplotlib notebook 彈出可交互的matplotlib窗口 %matplotlib qt5 彈出matplotlib控制臺(tái) %matplotlib inline 直接嵌入圖表,不需要使用plt.show()
保存圖片
plt.savefig("pic.png",dpi=100,bbox_inches="tight")

讀取圖片
方法一
from PIL import Image
image = Image.open("./pic.png")
image.show()

方法二
import matplotlib.pyplot as plt
X = plt.imread("./pic.png")
plt.imshow(X)

條形圖
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
a = np.arange(0,5,0.02)
plt.subplot(211)
plt.plot(a,f(a))
plt.subplot(212)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.show()

b = np.arange(0,2,0.02) plt.plot(b,np.sin(2*np.pi*b),'--',b,np.cos(2*np.pi*b),"*")

散點(diǎn)圖
import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = (30 * np.random.rand(N))**2 # 0 to 15 point radii plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show()

帶表格的圖形
import numpy as np
import matplotlib.pyplot as plt
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[139361, 331509, 343164, 781380, 52269]]
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
values = np.arange(0, 2500, 500)
value_increment = 1000
# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)
index = np.arange(len(columns)) + 0.3
bar_width = 0.4
# Initialize the vertical-offset for the stacked bar chart.
y_offset = np.zeros(len(columns))
# Plot bars and create text labels for the table
cell_text = []
for row in range(n_rows):
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()
# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='bottom')
# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)
plt.ylabel("Loss in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')
plt.show()

總結(jié)
到此這篇關(guān)于Python matplotlib實(shí)用繪圖技巧的文章就介紹到這了,更多相關(guān)matplotlib繪圖技巧內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python編程實(shí)現(xiàn)的圖片識(shí)別功能示例
這篇文章主要介紹了Python編程實(shí)現(xiàn)的圖片識(shí)別功能,涉及Python PIL模塊的安裝與使用技巧,需要的朋友可以參考下2017-08-08
詳解使用python繪制混淆矩陣(confusion_matrix)
這篇文章主要介紹了詳解使用python繪制混淆矩陣(confusion_matrix),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
對(duì)python中的float除法和整除法的實(shí)例詳解
今天小編就為大家分享一篇對(duì)python中的float除法和整除法的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
Python實(shí)現(xiàn)復(fù)制圖片到指定文件夾并按順序重新命名
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)將360個(gè)文件夾里的照片,全部復(fù)制到指定的文件夾中,并且按照順序重新命名,感興趣的小伙伴可以了解一下2023-03-03
Python Pygame實(shí)戰(zhàn)之實(shí)現(xiàn)經(jīng)營(yíng)類(lèi)游戲夢(mèng)想小鎮(zhèn)代碼版
作為一名模擬經(jīng)營(yíng)類(lèi)游戲的發(fā)燒友,各種農(nóng)場(chǎng)類(lèi)、醫(yī)院類(lèi)、鐵路類(lèi)的游戲玩兒了很多年。今天用代碼給大家打造一款夢(mèng)想小鎮(zhèn)游戲,希望大家喜歡啦2022-12-12
用Python實(shí)現(xiàn)QQ游戲大家來(lái)找茬輔助工具
這是一個(gè)用于QQ大家來(lái)找茬(美女找茬)的輔助外掛,開(kāi)發(fā)的原因是看到老爸天天在玩這個(gè)游戲,分?jǐn)?shù)是慘不忍睹的負(fù)4000多。本來(lái)是想寫(xiě)個(gè)很簡(jiǎn)單的東西,但由于過(guò)程中老爸的多次嘲諷,逼得我不得不盡力完善,最后形成了一個(gè)小小的產(chǎn)品。2014-09-09
django模型類(lèi)中,null=True,blank=True用法說(shuō)明
這篇文章主要介紹了django模型類(lèi)中,null=True,blank=True用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
基于Python?OpenCV和?dlib實(shí)現(xiàn)眨眼檢測(cè)
這篇文章主要介紹了基于Python?OPenCV及dlib實(shí)現(xiàn)檢測(cè)視頻流中的眨眼次數(shù)。文中的代碼對(duì)我們的學(xué)習(xí)和工作有一定價(jià)值,感興趣的同學(xué)可以參考一下2021-12-12
TensorFlow用expand_dim()來(lái)增加維度的方法
今天小編就為大家分享一篇TensorFlow用expand_dim()來(lái)增加維度的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07

