文章目錄
- 前言
- 一、基本組成
- 1、Figure
- 2、Axes
- 二、常見圖表的繪制
- 1、折線圖
- 2、柱形圖
- 3、餅圖
- 4、散點圖
- 5、泡泡圖
- 三、細節完善
- 1、坐標軸的完善(移動、“洗掉”)
- 2、刻度值的一些操作
- 3、圖例
- 4、添加注釋(如特殊點)
- 四、圖中圖
- 五、影片制圖
- 六、參考文章
- 七、Blogger's speech
相關文章鏈接:
python資料分析之pandas超詳細學習筆記
作者:遠方的星
CSDN:https://blog.csdn.net/qq_44921056
騰訊云:https://cloud.tencent.com/developer/column/91164
本文僅用于交流學習,未經作者允許,禁止轉載,更勿做其他用途,違者必究,
前言
這一篇是關于數分三劍客之一–matplotlib的一些學習筆記,
它的功能非常強大,可以讓枯燥的資料“美膩”起來,那么先來看一下官方給的一些樣圖:
官方提供的各種各樣的樣圖
一、基本組成
1、Figure
說到繪圖,那必須要有一個畫板,Figure作為一個“老畫板”,在matlab中經常能看到它的出沒,在python中,它的具體語法是什么呢?讓我們來看一下,
figure(num, figsize, dpi, facecolor, edgecolor, frameon)
- 六個引數的含義:
num:畫板的編號;
figsize:指定畫板的長和高;
dpi:繪圖物件的引數;
facecolor:背景顏色;
edgecolor:邊框顏色;
frameon:是否需要顯示邊框;
2、Axes
數學圖形怎么能離開坐標軸呢?
創建的方法不一、這里利用set函式創建坐標軸,
- set的五個引數含義:
xlim:x軸的范圍 [min,max];
ylim:y軸的范圍 [min,max];
xlable:自定義x軸的名稱;
ylable:自定義y軸的名稱;
title:自定義標題;
如:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[-2.5, 2.5], ylim=[-2.5, 2.5], xlabel='X', ylabel='Y', title='first-try')
plt.show()
輸出:(這里的櫻花樹,是pycharm的背景,不是代碼實作的效果)

看了上例,ax = fig.add_subplot(111)的作用是啥呀?
其實,這部分和matlab中的subplot作用一樣,就是在一個打的區域,布置“幾個”(可以是1個)畫板,
這里面的三個數字可以這么理解:第一個數字代表幾行,第二個數字代表幾列,第三個數字代表第幾個(順序是自左向右,自上到下)
如:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(224)
plt.show()
輸出:

二、常見圖表的繪制
- 開始之前,可以看一下大佬的這篇文章,介紹了很詳細的引數值:
matplotlib繪圖中與顏色相關的引數(color顏色引數、linestyle線型引數、marker標記引數)可選串列集合
1、折線圖
使用plt.plot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [1, 3, 2, 5, 9, 2]
# 傳進去x,y的坐標
plt.plot(x, y)
plt.show()
輸出:

2、柱形圖
使用plt.bar
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [1, 3, 2, 5, 9, 2]
# 傳進去x,y的坐標
plt.bar(x, y, color='blue')
plt.show()
輸出:

3、餅圖
使用plt.pie
import matplotlib.pyplot as plt
name = ['one', 'two', 'three', 'four', 'five', 'six']
x = [1, 3, 2, 5, 9, 2]
plt.pie(x, labels=name, colors=['b', 'r', 'g', 'k', 'c', 'm'])
plt.axis('equal')
plt.show()
輸出:

4、散點圖
使用plt.scatter
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [1, 3, 2, 5, 9, 2]
# market的作用是用什么記號來標記點
plt.scatter(x, y, color='red', marker='*')
plt.show()
輸出:

5、泡泡圖
在處理亂數的時候,感覺挺有意思的,
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(8, 8))
x = np.random.rand(50)
y = np.random.rand(50)
z = np.random.rand(50)
# color代表顏色,alpha代表透明度
plt.scatter(x, y, s=z * 1000, color='b', alpha=0.5)
plt.show()
輸出:

三、細節完善
1、坐標軸的完善(移動、“洗掉”)
對于坐標軸的改動,需要用到plt.gca函式,它有四個引數:top 、bottom、left、right,分別對應上下左右四個軸,如何操作,先看下面的例子,
- 這個是上面我第一次嘗試得到的結果圖:

- 改善之后可變成這樣(在畫函式影像時應該更舒服一些):

代碼:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[-2.5, 2.5], ylim=[-2.5, 2.5], title='first-try')
bx = plt.gca()
# 將下面的軸(x軸)設定為xaxis
bx.xaxis.set_ticks_position('bottom')
# 將設定后的軸移動到y=0的地方
bx.spines['bottom'].set_position(('data', 0))
bx.yaxis.set_ticks_position('left')
bx.spines['left'].set_position(('data', 0))
# 將不想看到的右、上方向的軸“洗掉”,其實就是把軸的顏色改為無色
bx.spines['top'].set_color('none')
bx.spines['right'].set_color('none')
plt.show()
2、刻度值的一些操作
- ①調整刻度值的大小、顏色、顯示情況
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[-2.5, 2.5], ylim=[-2.5, 2.5], title='first-try')
# 對x、y軸的刻度值進行設定
plt.yticks(fontsize=20, color='#00000') # y軸刻度值大小為20 ,顏色為黑色
# plt.yticks(fontsize=20, color='black') # 用black也可以
plt.xticks([]) # [] ,即不顯示x軸刻度值
plt.show()
輸出:

對于顏色轉換可以看一下這位大佬的總結:2020 RGB顏色查詢大全 #000000 【顏色串列】
- ②刻度值旋轉
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set(xlim=[-2.5, 2.5], ylim=[-2.5, 2.5], title='first-try')
fig.autofmt_xdate() # 默認旋轉45°,可以在括號里加rotation=‘角度’
plt.show()
3、圖例
import matplotlib.pyplot as plt
from numpy import *
x = linspace(0, 4, 50) # linspace(A,B,C),指從A開始B結束,中間分布C個值,C默認為100
y1 = x
y2 = x**2
plt.figure()
l1, = plt.plot(x, y1, color='b', linestyle='-')
l2, = plt.plot(x, y2, color='r', linestyle='--')
# handles:需要制作圖例的物件;labels:圖例的名字;loc:圖例的位置,loc的內容可選“best”,最佳位置
plt.legend(handles=[l1, l2], labels=['function1', 'function2'], loc='upper left')
plt.show()
注意:l1后面有個 ,
輸出:

4、添加注釋(如特殊點)
import matplotlib.pyplot as plt
from numpy import *
x = linspace(0, 4, 50) # linspace(A,B,C),指從A開始B結束,中間分布C個值,C默認為100
y = x**2
plt.figure()
# 選取需要標注的點
x0 = 1.5
y0 = x0**2
# 作圖
plt.plot(x, y)
# 作垂線,
plt.plot([x0, x0], [0, y0], 'k--', linewidth=1)
# 作出標注的點
plt.scatter([x0, ], [y0, ], s=50, color='b')
# 做標注
plt.annotate(r'$x^2=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
# 引數xycoords='data' 是說基于資料的值來選位置,
# xytext=(+30, -30) 和 textcoords='offset points' 對于標注位置的描述 和 xy 偏差值
# arrowprops是對圖中箭頭型別的一些設定
plt.show()
- arrowstyle的格式:
``'-'`` None
``'->'`` 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
輸出:

四、圖中圖
import matplotlib.pyplot as plt
from numpy import *
x = linspace(0, 4, 50) # linspace(A,B,C),指從A開始B結束,中間分布C個值,C默認為100
y = x**2
fig = plt.figure()
# 這四個數字分別代表的是相對figure的位置
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('main')
ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('children1')
ax3 = fig.add_axes([0.65, 0.2, 0.2, 0.2])
ax3.plot(y, x, 'b')
ax3.set_xlabel('x')
ax3.set_ylabel('y')
ax3.set_title('children2')
plt.show()
輸出:

這里系統會有提示:This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
意思為:此圖包括與緊韌體布局不兼容的軸,因此結果可能不正確,
五、影片制圖
前排提示:如果使用pycharm無法播放影片,可參考:pycharm中影片函式animation.FuncAnimation不起作用
實體參考
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), init_func=init, blit=True)
plt.show()
輸出:
(待更影片)
六、參考文章
參考文章1
參考文章2
參考文章3
參考文章4
參考文章5
參考文章6
參考文章7
七、Blogger’s speech
如有不足,還請大佬評論區留言或私信我,我會進行補充,
感謝您的支持,希望可以點贊,關注,收藏,一鍵三連喲,
作者:遠方的星
CSDN:https://blog.csdn.net/qq_44921056
騰訊云:https://cloud.tencent.com/developer/column/91164
本文僅用于交流學習,未經作者允許,禁止轉載,更勿做其他用途,違者必究,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/275438.html
標籤:其他
