最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python數(shù)據(jù)分析之Matplotlib的常用操作總結(jié)

 更新時間:2022年01月04日 15:45:52   作者:€€-飛翔?-~£  
Matplotlib是Python的繪圖庫,它可與NumPy一起使用,提供了一種有效的MatLab開源替代方案,下面這篇文章主要給大家介紹了關(guān)于Python數(shù)據(jù)分析之Matplotlib常用操作的相關(guān)資料,需要的朋友可以參考下

使用準備

使用matplotlib需引入:

import matplotlib.pyplot as plt

通常2會配合著numpy使用,numpy引入:

import numpy as np

1、簡單的繪制圖像

def matplotlib_draw():
    # 從-1到1生成100個點,包括最后一個點,默認為不包括最后一個點
    x = np.linspace(-1, 1, 100, endpoint=True)
 
    y = 2 * x + 1
    plt.plot(x, y)  # plot將信息傳入圖中
    plt.show()  # 展示圖片

2、視圖面板的常用操作

def matplotlib_figure():
    x = np.linspace(-1, 1, 100)
    y1 = 2 * x + 1
    y2 = x ** 2  # 平方
 
    plt.figure()  # figure是視圖面板
    plt.plot(x, y1)
 
    # 這里再創(chuàng)建一個視圖面板,最后會生成兩張圖,figure只繪制范圍以下的部分
    plt.figure(figsize=(4, 4))  # 設(shè)置視圖長寬
    plt.plot(x, y2)
 
    plt.show()

3、樣式及各類常用修飾屬性

def matplotlib_style():
    x = np.linspace(-3, 3, 100)
    y1 = 2 * x + 1
    y2 = x ** 2  # 平方
 
    # 限制xy輸出圖像的范圍
    plt.xlim((-1, 2))  # 限制x的范圍
    plt.ylim((-2, 3))  # 限制y的范圍
 
    # xy描述
    plt.xlabel('I am X')
    plt.ylabel('I am Y')
 
    # 設(shè)置xy刻度值
    # 從-2到2上取11個點,最后生成一個一維數(shù)組
    new_sticks = np.linspace(-2, 2, 11)
    plt.xticks(new_sticks)
    # 使用文字代替數(shù)字刻度
    plt.yticks([-1, 0, 1, 2, 3], ['level1', 'level2', 'level3', 'level4', 'level5'])
 
    # 獲取坐標軸 gca get current axis
    ax = plt.gca()
    ax.spines['right'].set_color('red')  # 設(shè)置右邊框為紅色
    ax.spines['top'].set_color('none')  # 設(shè)置頂部邊框為沒有顏色,即無邊框
 
    # 把x軸的刻度設(shè)置為'bottom'
    ax.xaxis.set_ticks_position('bottom')
    # 把y軸的刻度設(shè)置為'left'
    ax.yaxis.set_ticks_position('left')
    # 設(shè)置xy軸的位置,以下測試xy軸相交于(1,0)
    # bottom對應(yīng)到0點
    ax.spines['bottom'].set_position(('data', 0))
    # left對應(yīng)到1點
    ax.spines['left'].set_position(('data', 1))  # y軸會與1刻度對齊
 
    # 顏色、線寬、實線:'-',虛線:'--',alpha表示透明度
    plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5)
    plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-')
    plt.show()  # 這里沒有設(shè)置figure那么兩個線圖就會放到一個視圖里

4、legend圖例的使用

def matplotlib_legend():
    x = np.linspace(-3, 3, 100)
    y1 = 2 * x + 1
    y2 = x ** 2  # 平方
 
    l1, = plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5)
    l2, = plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-')
    # handles里面?zhèn)魅胍a(chǎn)生圖例的關(guān)系線,labels中傳入對應(yīng)的名稱,
    # loc='best'表示自動選擇最好的位置放置圖例
    plt.legend(handles=[l1, l2], labels=['test1', 'test2'], loc='best')
    plt.show()

5、添加文字等描述

def matplotlib_describe():
    x = np.linspace(-3, 3, 100)
    y = 2 * x + 1
    plt.plot(x, y, color="red", linewidth=1.0, linestyle='-')
 
    # 畫點,s表示點的大小
    x0 = 0.5
    y0 = 2 * x0 + 1
    plt.scatter(x0, y0, s=50, color='b')
 
    # 畫虛線,
    # k代表黑色,--代表虛線,lw線寬
    # 表示重(x0,y0)到(x0,-4)畫線
    plt.plot([x0, x0], [y0, -4], 'k--', lw=2)
    # 標注,xytext:位置,textcoords設(shè)置起始位置,arrowprops設(shè)置箭頭,connectionstyle設(shè)置弧度
    plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xytext=(+30, -30), 
                 textcoords="offset points", fontsize=16,
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
 
    # 文字描述
    plt.text(-3, 3, r'$this\ is\ the\ text$', fontdict={'size': '16', 'color': 'r'})
 
    plt.show()

6、不同類型圖像的繪制

(1)scatter繪制散點圖:

def matplotlib_scatter():
    plt.figure()
    plt.scatter(np.arange(5), np.arange(5))  # 安排兩個0到4的數(shù)組繪制
 
    x = np.random.normal(0, 1, 500)  # 正態(tài)分布的500個數(shù)
    y = np.random.normal(0, 1, 500)
 
    plt.figure()
    plt.scatter(x, y, s=50, c='b', alpha=0.5)
 
    plt.show()

(2)bar繪制直方圖:

def matplotlib_bar():
    x = np.arange(10)
    y = 2 ** x + 10
    # facecolor塊的顏色,edgecolor塊邊框的顏色
    plt.bar(x, y, facecolor='#9999ff', edgecolor='white')
    # 設(shè)置數(shù)值位置
    for x, y in zip(x, y):  # zip將x和y結(jié)合在一起
        plt.text(x + 0.4, y, "%.2f" % y, ha='center', va='bottom')
 
    plt.show()

(3)contour輪廓圖:

def matplotlib_contours():
    def f(a, b):
        return (1 - a / 2 + a ** 5 + b ** 3) * np.exp(-a ** 2 - b ** 2)
 
    x = np.linspace(-3, 3, 100)
    y = np.linspace(-3, 3, 100)
 
    X, Y = np.meshgrid(x, y)  # 將x和y傳入一個網(wǎng)格中
    # 8表示條形線的數(shù)量,數(shù)量越多越密集
    plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)  # cmap代表圖的顏色
 
    C = plt.contour(X, Y, f(X, Y), 8, color='black', linewidth=.5)
    plt.clabel(C, inline=True, fontsize=10)
 
    plt.xticks(())
    plt.yticks(())
    plt.show()

(4)3D圖:

3D圖繪制需額外再引入依賴:

from mpl_toolkits.mplot3d import Axes3D
def matplotlib_Axes3D():
    fig = plt.figure()  # 創(chuàng)建繪圖面版環(huán)境
    ax = Axes3D(fig)  # 將環(huán)境配置進去
 
    x = np.arange(-4, 4, 0.25)
    y = np.arange(-4, 4, 0.25)
    X, Y = np.meshgrid(x, y)  
    R = np.sqrt(X ** 2 + Y ** 2)
    Z = np.sin(R)
 
    # stride控制色塊大小
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
    ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')
    ax.set_zlim(-2, 2)
 
    plt.show()

 

(5)subplot子圖繪制:

def matplotlib_subplot():
    plt.figure()  # 生成繪圖面板
    plt.subplot(2, 1, 1)  # 兩行1列繪圖位置的第1個位置
    plt.plot([0, 1], [0, 1])  # 繪制從(0,0)繪制到(1,1)的圖像
    plt.subplot(2, 3, 4)  # 兩行3列繪圖位置的第4個位置
    plt.plot([0, 1], [0, 1])  # 繪制從(0,0)繪制到(1,1)的圖像
    plt.subplot(2, 3, 5)  # 兩行3列繪圖位置的第5個位置
    plt.plot([0, 1], [0, 1])  # 繪制從(0,0)繪制到(1,1)的圖像
    plt.subplot(2, 3, 6)  # 兩行3列繪圖位置的第6個位置
    plt.plot([0, 1], [0, 1])  # 繪制從(0,0)繪制到(1,1)的圖像
 
    plt.show()

(6)animation動圖繪制

需額外導(dǎo)入依賴:

from matplotlib import animation
# ipython里運行可以看到動態(tài)效果
def matplotlib_animation():
    fig, ax = plt.subplots()
 
    x = np.arange(0, 2 * np.pi, 0.01)
    line, = ax.plot(x, np.sin(x))
 
    def animate(i):
        line.set_ydata(np.sin(x + i / 10))
        return line,
 
    def init():
        line.set_ydata(np.sin(x))
        return line,
 
    ani = animation.FuncAnimation(fig=fig, func=animate, init_func=init, interval=20)
 
    plt.show()

附:直方圖代碼實現(xiàn)

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(1)
# 產(chǎn)生30個學生身高數(shù)據(jù)
hight = np.random.randint(low=140, high=190, size=30)
print("身高數(shù)據(jù)", hight)

# 繪制直方圖 plt.hist

# 參數(shù)1:要統(tǒng)計的數(shù)據(jù); 參數(shù)2:區(qū)間信息

# 區(qū)間信息有默認值 bins =10 ?分10組
# bins = [140, 145, 160, 170, 190]
# 除了最后一個 都是前閉后開;最后一組是前閉后閉
# [140,145) [145,160) [160,170) [170,190]

bins = [140, 180, 190]

cnt, bins_info, _ = plt.hist(hight,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?bins=10,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# bins=bins,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?edgecolor='w' ?# 柱子的邊緣顏色 白色
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?)
# 直方圖的返回值有3部分內(nèi)容
# 1. 每個區(qū)間的數(shù)據(jù)量
# 2. 區(qū)間信息
# 3. 區(qū)間內(nèi)數(shù)據(jù)數(shù)據(jù)信息 是個對象 不能直接查看
# print("直方圖的返回值", out)

# cnt, bins_info, _ = out


# 修改x軸刻度
plt.xticks(bins_info)

# 增加網(wǎng)格線
# 參數(shù)1:b bool類型 是否增加網(wǎng)格線
# 參數(shù) axis 網(wǎng)格線 垂直于 哪個軸
plt.grid(b=True,
? ? ? ? ?axis='y',
? ? ? ? ?# axis='both'
? ? ? ? ?alpha=0.3
? ? ? ? ?)

# 增加標注信息 plt.text
print("區(qū)間信息", bins_info)
print("區(qū)間數(shù)據(jù)量", cnt)

bins_info_v2 = (bins_info[:-1] + bins_info[1:]) / 2
for i, j in zip(bins_info_v2, cnt):
? ? # print(i, j)
? ? plt.text(i, j + 0.4, j,
? ? ? ? ? ? ?horizontalalignment='center', ?# 水平居中
? ? ? ? ? ? ?verticalalignment='center', ?# 垂直居中
? ? ? ? ? ? ?)

# 調(diào)整y軸刻度
plt.yticks(np.arange(0, 20, 2))

plt.show()

更多見官方文檔:教程 | Matplotlib 中文

總結(jié)

到此這篇關(guān)于Python數(shù)據(jù)分析之Matplotlib常用操作的文章就介紹到這了,更多相關(guān)Python Matplotlib常用操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python3.5面向?qū)ο笈c繼承圖文實例詳解

    Python3.5面向?qū)ο笈c繼承圖文實例詳解

    這篇文章主要介紹了Python3.5面向?qū)ο笈c繼承,結(jié)合圖文與實例形式詳細分析了Python3.5面向?qū)ο笈c繼承的相關(guān)概念、原理、實現(xiàn)方法及操作注意事項,需要的朋友可以參考下
    2019-04-04
  • Python創(chuàng)建一個自定義視頻播放器的實現(xiàn)

    Python創(chuàng)建一個自定義視頻播放器的實現(xiàn)

    本文主要介紹了Python創(chuàng)建一個自定義視頻播放器的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • 對Python中內(nèi)置異常層次結(jié)構(gòu)詳解

    對Python中內(nèi)置異常層次結(jié)構(gòu)詳解

    今天小編就為大家分享一篇對Python中內(nèi)置異常層次結(jié)構(gòu)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • 深入了解如何基于Python讀寫Kafka

    深入了解如何基于Python讀寫Kafka

    這篇文章主要介紹了深入了解如何基于Python讀寫Kafka,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-12-12
  • python基于phantomjs實現(xiàn)導(dǎo)入圖片

    python基于phantomjs實現(xiàn)導(dǎo)入圖片

    這篇文章主要介紹了python基于phantomjs實現(xiàn)導(dǎo)入圖片的相關(guān)資料,需要的朋友可以參考下
    2016-05-05
  • Python使用Selenium與pytest進行高效測試的示例詳解

    Python使用Selenium與pytest進行高效測試的示例詳解

    隨著軟件開發(fā)的快速發(fā)展,自動化測試成為了提高開發(fā)效率、降低錯誤率的重要工具,Python作為一種高效且易于使用的編程語言,已經(jīng)成為自動化測試領(lǐng)域的重要工具之一,本文將介紹如何使用Python、Selenium和pytest進行自動化測試,并展示一個簡單的自動化測試示例
    2025-01-01
  • 深入理解python函數(shù)遞歸和生成器

    深入理解python函數(shù)遞歸和生成器

    下面小編就為大家?guī)硪黄钊肜斫鈖ython函數(shù)遞歸和生成器。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-06-06
  • 如何使用python讀取Excel指定范圍并轉(zhuǎn)為數(shù)組

    如何使用python讀取Excel指定范圍并轉(zhuǎn)為數(shù)組

    python處理數(shù)據(jù)文件的途徑有很多種,下面這篇文章主要給大家介紹了關(guān)于如何使用python讀取Excel指定范圍并轉(zhuǎn)為數(shù)組的相關(guān)資料,文中通過圖文以及實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-11-11
  • python使用cv2庫、下載opencv庫的方法

    python使用cv2庫、下載opencv庫的方法

    這篇文章主要介紹了python使用cv2庫、下載opencv庫的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-04-04
  • Python多元非線性回歸及繪圖的實現(xiàn)

    Python多元非線性回歸及繪圖的實現(xiàn)

    本文主要介紹了Python多元非線性回歸及繪圖的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-04-04

最新評論

五常市| 札达县| 虞城县| 山丹县| 宜章县| 营口市| 闸北区| 洛扎县| 永寿县| 鸡泽县| 咸宁市| 镶黄旗| 伊宁县| 舟山市| 天气| 新兴县| 吉水县| 景东| 宜都市| 洱源县| 清原| 南乐县| 麦盖提县| 德州市| 赫章县| 卓尼县| 明星| 二手房| 姚安县| 东乌| 阜平县| 灵寿县| 固阳县| 共和县| 青川县| 临安市| 永靖县| 集安市| 瓮安县| 盐山县| 定陶县|