国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python 繪制數(shù)據(jù)圖表

這篇具有很好參考價值的文章主要介紹了Python 繪制數(shù)據(jù)圖表。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

Python 繪制數(shù)據(jù)圖表

  • matplotlib繪圖庫模塊安裝
pip install matplotlib

Python 繪制數(shù)據(jù)圖表

  • 導(dǎo)入pyplot子模塊
import matplotlib.pyplot as plt
  • 官網(wǎng):http://matplotlib.org
  • 官方文檔:https://matplotlib.org/stable/index.html

1. 繪制折線圖

1.1 繪制簡單的折線圖

import matplotlib
import matplotlib.pyplot as plt

# 設(shè)置字體為微軟雅黑,解決中文顯示問題
matplotlib.rc("font", family='Microsoft YaHei')

# 1.準(zhǔn)備數(shù)據(jù)
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 2.畫線plot()
# linewidth設(shè)置線條寬度
plt.plot(squares, linewidth=2)  # 列表內(nèi)的數(shù)據(jù)被視為y軸的值,x軸的值會根據(jù)列表值的索引位置自動產(chǎn)生

# 3.設(shè)置x、y軸的最小刻度和最大刻度
plt.axis([0, 10, 0, 100])  # 將x軸設(shè)為0~10,將y軸設(shè)為0~100

# 4.設(shè)置標(biāo)題及字體大小
"""
title():圖表標(biāo)題,title(標(biāo)題名稱,fontsize=字體大小)
xlabel():x軸標(biāo)題
ylabel():y軸標(biāo)題
"""
plt.title(label='0~10的平方', fontsize=18)
plt.xlabel(xlabel='值', fontsize=15)
plt.ylabel(ylabel='平方值', fontsize=15)

# 5.設(shè)置坐標(biāo)軸刻度
"""
使用tick_params()方法設(shè)置:
    - 應(yīng)用范圍(axis):x-->應(yīng)用到x軸,y-->應(yīng)用到y(tǒng)軸,both-->應(yīng)用到x軸和y軸
    - 坐標(biāo)軸的刻度大?。╨abelsize)
    - 線條顏色(color)
如:tick_params(axis='x', labelsize=10, color='green')
"""
plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')

# 顯示繪制的圖形
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

1.2 修改圖表的初始值

import matplotlib
import matplotlib.pyplot as plt

# 設(shè)置字體為微軟雅黑,解決中文顯示問題
matplotlib.rc("font", family='Microsoft YaHei')

# 1.準(zhǔn)備數(shù)據(jù)
squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 索引列表
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 2.畫線plot()
# linewidth設(shè)置線條寬度
plt.plot(seq, squares, linewidth=2.5)

# 設(shè)置標(biāo)題及字體大小
plt.title(label='1~10的平方', fontsize=18)
plt.xlabel(xlabel='值', fontsize=15)
plt.ylabel(ylabel='平方值', fontsize=15)

# 5.設(shè)置坐標(biāo)軸刻度
plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')

# 顯示繪制的圖形
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

1.3 多組數(shù)據(jù)的應(yīng)用

# author:mlnt
# createdate:2022/8/17

import matplotlib
import matplotlib.pyplot as plt

# 設(shè)置字體為微軟雅黑,解決中文顯示問題
matplotlib.rc("font", family='Microsoft YaHei')

# 1.準(zhǔn)備數(shù)據(jù)
data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]

# 索引列表
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 2.畫線plot()
# linewidth設(shè)置線條寬度
plt.plot(seq, data1, seq, data2, linewidth=2.5)

# 設(shè)置標(biāo)題及字體大小
plt.title(label='Test Chart', fontsize=18)
plt.xlabel(xlabel='x-value', fontsize=14)
plt.ylabel(ylabel='y-value', fontsize=14)

# 5.設(shè)置坐標(biāo)軸刻度
plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')

# 顯示繪制的圖形
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

1.4 設(shè)置線條顏色及樣式

  • 設(shè)置顏色,可在plot()中添加參數(shù):

    • ‘b’: blue
    • ‘c’: cyan
    • ‘g’: green
    • ‘k’: black
    • ‘m’: magenta
    • ‘r’: red
    • ‘w’: white
    • ‘y’: yellow
  • 設(shè)置線條樣式:

    • '-‘或’solid’: 預(yù)設(shè)實(shí)線
    • '–‘或’dashed’: 虛線
    • '-.‘或’dashdot’: 虛點(diǎn)線
    • ':‘或’dotted’:點(diǎn)線
    • ‘.’:點(diǎn)標(biāo)記
    • ‘,’:像素標(biāo)記
    • ‘o’: 圓標(biāo)記
    • ‘v’: 反三角標(biāo)記
    • ‘^’: 三角標(biāo)記
    • ‘s’:方形標(biāo)記
    • ‘p’:五角標(biāo)記
    • ‘*’: 星號標(biāo)記
    • ‘+’:加號標(biāo)記
    • ‘-’:減號標(biāo)記
    import matplotlib.pyplot as plt
    
    # 1.準(zhǔn)備數(shù)據(jù)
    data1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]            # data1線條
    data2 = [1, 4, 9, 16, 25, 36, 49, 64, 81]      # data2線條
    data3 = [1, 3, 5, 8, 13, 21, 34, 55, 89]       # data3線條
    data4 = [1, 6, 12, 20, 30, 41, 56, 72, 90]     # data4線條
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    plt.plot(seq, data1, 'g--', seq, data2, 'r-.', seq, data3, 'b:', seq, data4, 'mp')
    
    # 設(shè)置標(biāo)題及字體大小
    plt.title(label='Test Chart', fontsize=18)
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 設(shè)置坐標(biāo)軸刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    
    plt.show()
    

效果:
Python 繪制數(shù)據(jù)圖表

1.5 刻度設(shè)置

import matplotlib
import matplotlib.pyplot as plt

# 設(shè)置字體為微軟雅黑,解決中文顯示問題
matplotlib.rc("font", family='Microsoft YaHei')
# 1.準(zhǔn)備數(shù)據(jù)
gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]

# 索引列表
year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]


"""
設(shè)置刻度:
- xticks():設(shè)置x軸刻度
- yticks():設(shè)置y軸刻度
"""
# 設(shè)置x軸刻度
plt.xticks(year)

# 設(shè)置線條樣式
plt.plot(year, gold_medal, '-*', year, silver_medal, '-o', year, bronze_medal, '-^')

# 設(shè)置標(biāo)題及字體大小
plt.title('中國歷屆奧運(yùn)會獎牌情況', fontsize=20)
plt.xlabel('年份', fontsize=14)
plt.ylabel('數(shù)量/枚', fontsize=14)
# 設(shè)置坐標(biāo)軸刻度
plt.tick_params(axis='both', labelsize=12, color='red')
# 顯示圖表
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

1.6 圖例legend()

參數(shù)loc可以設(shè)置圖例的位置:

  • ‘best’: 0,
  • ‘upper right’: 1 ,–>右上角
  • ‘upper left’: 2,–>左上角
  • ‘lower left’: 3,–>左下角
  • ‘lower right’: 4,–>右下角
  • ‘right’: 5,
  • ‘center left’: 6,–>左側(cè)中央
  • ‘center right’: 7,–>右側(cè)中間
  • ‘lower center’: 8,–>底部正中
  • ‘upper center’: 9,–>頂部正中
  • ‘center’: 10
  • 將圖例放在圖表內(nèi)
import matplotlib
import matplotlib.pyplot as plt

# 設(shè)置字體為微軟雅黑,解決中文顯示問題
matplotlib.rc("font", family='Microsoft YaHei')
# 1.準(zhǔn)備數(shù)據(jù)
gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]

# 索引列表
year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]


"""
設(shè)置刻度:
- xticks():設(shè)置x軸刻度
- yticks():設(shè)置y軸刻度
"""
# 設(shè)置x軸刻度
plt.xticks(year)

# 設(shè)置線條樣式
line_gold, = plt.plot(year, gold_medal, '-*', label='gold_medal')
line_silver, = plt.plot(year, silver_medal, '-o', label='silver_medal')
line_bronze, = plt.plot(year, bronze_medal, '-^', label='bronze_medal')

# 設(shè)置圖例
"""
參數(shù)loc可以設(shè)置圖例的位置
    'best': 0,
    'upper right': 1,-->右上角
    'upper left': 2,-->左上角
    'lower left': 3,-->左下角
    'lower right': 4,-->右下角
    'right': 5,
    'center left': 6,-->左側(cè)中央
    'center right': 7,-->右側(cè)中間
    'lower center': 8,-->底部正中
    'upper center': 9,-->頂部正中
    'center': 10
"""
plt.legend(handles=[line_gold, line_silver, line_bronze], loc='best')
# 放在圖表內(nèi)的右上角
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc=1)
# 放在圖表內(nèi)的左上角
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='upper left')
# 放在圖表內(nèi)的左下角
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc=3)
# 放在圖表內(nèi)的右下角
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc=4)

# 放在圖表內(nèi)的左側(cè)中央
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='center left')
# 放在圖表內(nèi)的右側(cè)中央
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='center right')
# 放在圖表內(nèi)的底部正中
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='lower center')
# 放在圖表內(nèi)的頂部正中
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='upper center')

# 設(shè)置標(biāo)題及字體大小
plt.title('中國歷屆奧運(yùn)會獎牌情況', fontsize=20)
plt.xlabel('年份', fontsize=14)
plt.ylabel('數(shù)量/枚', fontsize=14)
# 設(shè)置坐標(biāo)軸刻度
plt.tick_params(axis='both', labelsize=12, color='red')
# 顯示圖表
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

  • 將圖例放在圖表外,使用savefig()方法保存圖片文件

    # author:mlnt
    # createdate:2022/8/17
    import matplotlib
    import matplotlib.pyplot as plt
    
    # 設(shè)置字體為微軟雅黑,解決中文顯示問題
    matplotlib.rc("font", family='Microsoft YaHei')
    # 1.準(zhǔn)備數(shù)據(jù)
    gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
    silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
    bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]
    
    # 索引列表
    year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    
    
    """
    設(shè)置刻度:
    - xticks():設(shè)置x軸刻度
    - yticks():設(shè)置y軸刻度
    """
    # 設(shè)置x軸刻度
    plt.xticks(year)
    
    # 設(shè)置線條樣式
    line_gold, = plt.plot(year, gold_medal, '-*', label='gold_medal')
    line_silver, = plt.plot(year, silver_medal, '-o', label='silver_medal')
    line_bronze, = plt.plot(year, bronze_medal, '-^', label='bronze_medal')
    
    # 設(shè)置圖例
    # bbox_to_anchor()設(shè)置錨點(diǎn),即圖例位置
    # 在圖表內(nèi),左下角位置為(0,0),右上角位置為(1,1)
    plt.legend(handles=[line_gold, line_silver, line_bronze], loc='best', bbox_to_anchor=(1, 1))
    
    # 設(shè)置在圖表與Figure 1之間留白
    # h_pad/w_pad分別設(shè)置高度/寬度的留白
    plt.tight_layout(pad=2)
    
    
    # 設(shè)置標(biāo)題及字體大小
    plt.title('中國歷屆奧運(yùn)會獎牌情況', fontsize=20)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('數(shù)量/枚', fontsize=14)
    # 設(shè)置坐標(biāo)軸刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    
    # 保存圖片文件,使用savefig()方法保存圖片文件,需放在show()的前面,表示先存儲再顯示圖表
    plt.savefig('medal_chart.jpg', bbox_inches='tight')  # bbox_inches='tight'將圖表的多余空間刪除
    
    # 顯示圖表
    plt.show()
    

    效果:
    Python 繪制數(shù)據(jù)圖表

2. 繪制散點(diǎn)圖

2.1 基本散點(diǎn)圖的繪制

  • 繪制一個點(diǎn)
"""
scatter(x, y, s, c)
s: 繪圖點(diǎn)的大小
c:顏色
"""
import matplotlib.pyplot as plt

# 在坐標(biāo)軸(5,5)繪制一個點(diǎn)
plt.scatter(5, 5)
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

  • 繪制系列點(diǎn)

    # author:mlnt
    # createdate:2022/8/17
    """
    scatter(x, y, s, c)
    s: 繪圖點(diǎn)的大小
    c:顏色
    """
    import matplotlib.pyplot as plt
    
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 顯示中文標(biāo)簽
    plt.rcParams['axes.unicode_minus'] = False
    
    medal = [32, 28, 54, 50, 59, 63, 100, 88, 70, 88]
    # 索引列表
    year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    
    # 設(shè)置x軸刻度
    plt.xticks(year)
    
    plt.scatter(x=year, y=medal, s=20, c='green')
    
    # 設(shè)置標(biāo)題及字體大小
    plt.title('中國歷屆奧運(yùn)會獎牌情況', fontsize=20)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('數(shù)量/枚', fontsize=14)
    # 設(shè)置坐標(biāo)軸刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    plt.show()
    

    效果:
    Python 繪制數(shù)據(jù)圖表

2.2 設(shè)置繪制區(qū)間

**axis()**設(shè)置繪圖區(qū)間:

  • axis([xmin, xmax, ymin, ymax])
    • xmin/xmax:x軸的最小/最大區(qū)間
    • ymin/ymxa:y軸的最小/最大區(qū)間
# author:mlnt
# createdate:2022/8/17
"""
axis()設(shè)置繪圖區(qū)間:
axis([xmin, xmax, ymin, ymax])
xmin/xmax:x軸的最小/最大區(qū)間
ymin/ymxa:y軸的最小/最大區(qū)間
"""

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = [i for i in range(1, 101)]
y = [i**2 for i in x]

# 設(shè)置繪圖區(qū)間
plt.axis([0, 100, 0, 10000])
plt.scatter(x=x, y=y, s=20, c='green')

# 設(shè)置標(biāo)題及字體大小
plt.title('1-100的平方', fontsize=20)
plt.xlabel('數(shù)值', fontsize=14)
plt.ylabel('平方值', fontsize=14)
# 設(shè)置坐標(biāo)軸刻度
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

2.3 繪制波形

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 500)
# 繪制sin()和cos()的波形變化
y1 = np.sin(x)
y2 = np.cos(x)
plt.scatter(x, y1, color=(0.5, 0.8, 0.6))
plt.scatter(x, y2)
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

2.4 創(chuàng)建不等寬的散點(diǎn)圖

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 500)
y = 1 - 0.5*np.abs(x-2)
lwidths = (1+x)**2
plt.scatter(x=x, y=y, s=lwidths, color=(0.6, 0.8, 0.9))
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

2.5 色彩映射

import matplotlib.pyplot as plt
import numpy as np


x = np.arange(100)
plt.scatter(x=x, y=x, c=x, cmap='rainbow')
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

2.6 利用隨機(jī)數(shù)繪制散點(diǎn)圖

import matplotlib.pyplot as plt
import numpy as np

while True:
    x = np.random.random(100)
    y = np.random.random(100)
    t = x
    plt.scatter(x, y, s=100, c=t, cmap='brg')
    plt.show()
    is_exit = input('是否繼續(xù)?(y/n)')
    if is_exit.upper() == 'N':
        break

Python 繪制數(shù)據(jù)圖表

2.7 利用隨機(jī)數(shù)實(shí)現(xiàn)位置的移動

# author:mlnt
# createdate:2022/8/17
import random

import matplotlib.pyplot as plt


def loc(index):
    """處理坐標(biāo)的移動"""
    x_mov = random.choice([-3, 3])
    xloc = x[index - 1] + x_mov
    y_mov = random.choice([-5, -1, 1, 5])
    yloc = y[index - 1] + y_mov
    x.append(xloc)
    y.append(yloc)


num = 8000
x = [0]
y = [0]

while True:
    for i in range(1, num):
        loc(i)

    t = x
    plt.scatter(x, y, s=2, c=t, cmap='brg')
    # plt.axes().get_xaxis().set_visible(False)  # 隱藏y坐標(biāo)
    # plt.axes().get_yaxis().set_visible(False)  # 隱藏y坐標(biāo)
    # 隱藏坐標(biāo)軸。
    plt.axis('off')
    plt.savefig('image.png', bbox_inches='tight', pad_inches=0)
    plt.show()
    is_exit = input('是否繼續(xù)?(y/n)')
    if is_exit.upper() == 'N':
        break
    else:
        x[0] = x[num - 1]
        y[0] = y[num - 1]
        del x[1:]
        del y[1:]

Python 繪制數(shù)據(jù)圖表

3. 繪制多個圖表

3.1 一個程序繪制多個圖表

# author:mlnt
# createdate:2022/8/17
import matplotlib.pyplot as plt

# 1.準(zhǔn)備數(shù)據(jù)
data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]

# 索引列表
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]


# 創(chuàng)建圖表1
plt.figure(1)
# 畫線plot()
plt.plot(seq, data1, '-*')

# 創(chuàng)建圖表2
plt.figure(2)
plt.plot(seq, data2, '-o')
# 設(shè)置標(biāo)題及字體大小
plt.title(label='Test Chart 2', fontsize=18)
plt.xlabel(xlabel='x-value', fontsize=14)
plt.ylabel(ylabel='y-value', fontsize=14)

# 5.設(shè)置坐標(biāo)軸刻度
plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')

# 顯示繪制的圖形
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

3.2 含有子表的圖表

subplot(x1, x2, x3)

  • x1: 上下(垂直)方向繪制圖表數(shù)
  • x2:左右(水平)方向繪制圖表數(shù)
  • x3:表示這是第幾張
  • 一個Figure內(nèi)繪制上下子圖

    # author:mlnt
    # createdate:2022/8/17
    """
    subplot(x1, x2, x3)
    x1: 上下(垂直)方向繪制圖表數(shù)
    x2:左右(水平)方向繪制圖表數(shù)
    x3:表示這是第幾張
    """
    import matplotlib.pyplot as plt
    
    # 1.準(zhǔn)備數(shù)據(jù)
    data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
    data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # 在一個Figure內(nèi)繪制上下子圖
    plt.subplot(2, 1, 1)
    # 畫線plot()
    plt.plot(seq, data1, '-*')
    
    plt.subplot(2, 1, 2)
    plt.plot(seq, data2, '-o')
    # 設(shè)置標(biāo)題及字體大小
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 設(shè)置坐標(biāo)軸刻度
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 顯示繪制的圖形
    plt.show()
    

    效果:
    Python 繪制數(shù)據(jù)圖表

  • 一個Figure內(nèi)繪制左右子圖

    # author:mlnt
    # createdate:2022/8/17
    """
    subplot(x1, x2, x3)
    x1: 上下(垂直)方向繪制圖表數(shù)
    x2:左右(水平)方向繪制圖表數(shù)
    x3:表示這是第幾張
    """
    import matplotlib.pyplot as plt
    
    # 1.準(zhǔn)備數(shù)據(jù)
    data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
    data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # 在一個Figure內(nèi)繪制上下子圖
    plt.subplot(2, 1, 1)
    # 畫線plot()
    plt.plot(seq, data1, '-*')
    
    plt.subplot(2, 1, 2)
    plt.plot(seq, data2, '-o')
    # 設(shè)置標(biāo)題及字體大小
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 設(shè)置坐標(biāo)軸刻度
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 顯示繪制的圖形
    plt.show()
    

    效果:
    Python 繪制數(shù)據(jù)圖表

4. 繪制直方圖

# author:mlnt
# createdate:2022/8/17
"""
bar(x, height, width)
x: 序列,x軸位置
height:序列數(shù)值大小
width:直方圖的寬度
"""
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei'] # 顯示中文標(biāo)簽
plt.rcParams['axes.unicode_minus'] = False

medal = [32, 28, 54, 50, 59, 63, 100, 88, 70, 88]
x = np.arange(len(medal))
# 索引列表
year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]

plt.bar(x, medal, width=0.5)

# 設(shè)置標(biāo)題及字體大小
plt.title('中國歷屆奧運(yùn)會獎牌情況', fontsize=20)
plt.xlabel('年份', fontsize=14)
plt.ylabel('數(shù)量/枚', fontsize=14)
plt.xticks(x, year)
# 設(shè)置坐標(biāo)軸刻度
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

# author:mlnt
# createdate:2022/8/17
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 1.準(zhǔn)備數(shù)據(jù)
labels = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]

x = np.arange(len(labels))  # x軸位置
width = 0.3  # 直方圖的寬度

fig, ax = plt.subplots()
rects1 = ax.bar(x - width, gold_medal, width, label='gold_medal')
rects2 = ax.bar(x, silver_medal, width, label='silver_medal')
rects3 = ax.bar(x + width, bronze_medal, width, label='bronze_medal')

# 設(shè)置標(biāo)題及字體大小
ax.set_xlabel('年份', fontsize=14)
ax.set_ylabel('數(shù)量/枚', fontsize=14)
ax.set_title('中國歷屆奧運(yùn)會獎牌情況', fontsize=20)
ax.set_xticks(x, labels)
# 設(shè)置圖例
ax.legend()

ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)
ax.bar_label(rects3, padding=3)

fig.tight_layout()

plt.show()

效果:
Python 繪制數(shù)據(jù)圖表

5. 使用CSV文件繪制圖表

# author:mlnt
# createdate:2022/8/17
import csv

import matplotlib
import matplotlib.pyplot as plt

matplotlib.rc("font", family='Microsoft YaHei')

filename = 'score.csv'

with open(file=filename) as csvFile:    # 打開csv文件
    csvReader = csv.reader(csvFile)    # 創(chuàng)建reader對象
    headerRow = next(csvReader)   # 讀取文件下一行
    print(headerRow)  # ['學(xué)號', '姓名', '語文', '數(shù)學(xué)', '英語', '物理', '化學(xué)', '生物']
    # 設(shè)置空列表
    names, Chinese, Math, English, Physics, Chemistry, Biology = [], [], [], [], [], [], []
    for row in csvReader:
        # 將數(shù)據(jù)添加到列表
        names.append(row[1])
        Chinese.append(int(row[2]))
        Math.append(int(row[3]))
        English.append(int(row[4]))
        Physics.append(int(row[5]))
        Chemistry.append(int(row[6]))
        Biology.append(int(row[7]))
    print(f'語文:{Chinese}')
    print(f'數(shù)學(xué):{Math}')
    print(f'英語:{English}')
    print(f'物理:{Physics}')
    print(f'化學(xué):{Chemistry}')
    print(f'生物:{Biology}')

# 繪制語文成績
# 設(shè)置繪圖區(qū)大小
fig = plt.figure(dpi=80, figsize=(12, 8))
# 設(shè)置線條樣式
line_Chinese, = plt.plot(names, Chinese, '-*', label='Chinese')
line_Math, = plt.plot(names, Math, '-o', label='Math')
line_English, = plt.plot(names, English, '-p', label='English')
line_Physics, = plt.plot(names, Physics, '-s', label='Physics')
line_Chemistry, = plt.plot(names, Chemistry, '-v', label='Chemistry')
line_Biology, = plt.plot(names, Biology, '-^', label='Biology')
# 設(shè)置圖例
plt.legend(handles=[line_Chinese, line_Math, line_English, line_Physics, line_Chemistry, line_Biology], loc='best')
# 旋轉(zhuǎn)
fig.autofmt_xdate(rotation=60)
plt.title('成績分析', fontsize=20)
plt.xlabel('學(xué)員', fontsize=14)
plt.ylabel('分?jǐn)?shù)', fontsize=14)
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

score.csv:
Python 繪制數(shù)據(jù)圖表

效果:
Python 繪制數(shù)據(jù)圖表

# author:mlnt
# createdate:2022/8/17
import csv
from datetime import datetime

import matplotlib
import matplotlib.pyplot as plt

matplotlib.rc("font", family='Microsoft YaHei')

filename = 'temperature.csv'

with open(file=filename) as csvFile:    # 打開csv文件
    csvReader = csv.reader(csvFile)    # 創(chuàng)建reader對象
    headerRow = next(csvReader)   # 讀取文件下一行
    # print(headerRow)
    # 設(shè)置空列表
    dates, lowTemps, highTemps, averageTemps = [], [], [], []
    for row in csvReader:
        try:
            # 將日期字符串轉(zhuǎn)成對象
            currentDate = datetime.strptime(row[0], '%Y/%m/%d')
            # 設(shè)置最低溫度
            # 需要轉(zhuǎn)換成數(shù)字類型,y軸才能進(jìn)行排序
            lowTemp = float(row[1])
            # 設(shè)置最高溫度
            highTemp = float(row[2])
            # 設(shè)置平均溫度
            averageTemp = float(row[3])
        except Exception as e:
            print('有缺值', e)
        else:
            # 將數(shù)據(jù)添加到列表
            dates.append(currentDate)
            lowTemps.append(lowTemp)
            highTemps.append(highTemp)
            averageTemps.append(averageTemp)
    print(f'最低溫度:{lowTemps}')
    print(f'最高溫度:{highTemps}')
    print(f'平均溫度:{averageTemps}')


# # 設(shè)置繪圖區(qū)大小
fig = plt.figure(dpi=80, figsize=(12, 8))
# 設(shè)置線條樣式
line_highTemps, = plt.plot(dates, highTemps, '-*', label='highTemps')
line_lowTemps, = plt.plot(dates, lowTemps, '-o', label='lowTemps')
line_averageTemps, = plt.plot(dates, averageTemps, '-p', label='averageTemps')
# 設(shè)置圖例
plt.legend(handles=[line_lowTemps, line_averageTemps, line_highTemps], loc='best')
# 旋轉(zhuǎn)
fig.autofmt_xdate(rotation=60)
plt.title('Weather Report', fontsize=20)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Temperature (C)', fontsize=14)
plt.tick_params(axis='both', labelsize=12, color='red')
plt.show()

temperature.csv:
Python 繪制數(shù)據(jù)圖表
效果:
Python 繪制數(shù)據(jù)圖表文章來源地址http://www.zghlxwxcb.cn/news/detail-451454.html


參考:
  • 官網(wǎng):http://matplotlib.org
  • 官方文檔:https://matplotlib.org/stable/index.html
  • 色彩映射:http://matplotlib.org/examples/color/colormaps_reference.html
  • https://blog.csdn.net/weixin_46233323/article/details/108038706
  • https://blog.csdn.net/weixin_43838785/article/details/104515455
  • https://blog.csdn.net/weixin_41783077/article/details/110734759
  • https://www.pudn.com/news/62623526dfdd9a1c0c529522.html
  • https://www.yzlfxy.com/jiaocheng/python/430158.html
  • https://www.zhihu.com/question/506015285

到了這里,關(guān)于Python 繪制數(shù)據(jù)圖表的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 數(shù)據(jù)可視化:圖表繪制詳解

    數(shù)據(jù)可視化是一種將抽象的數(shù)字和數(shù)據(jù)轉(zhuǎn)化為直觀圖形的技術(shù),使數(shù)據(jù)的模式、趨勢和關(guān)系一目了然。本文將詳細(xì)介紹如何繪制各種類型的圖表,包括柱狀圖、折線圖、餅圖、散點(diǎn)圖和熱力圖等。 第一部分:圖表類型和選擇 1. 柱狀圖 柱狀圖是用于比較類別數(shù)據(jù)的常見圖表。

    2024年02月12日
    瀏覽(34)
  • 第五章. 可視化數(shù)據(jù)分析圖表—常用圖表的繪制4—箱形圖,3D圖表

    第五章. 可視化數(shù)據(jù)分析圖表—常用圖表的繪制4—箱形圖,3D圖表

    第五章. 可視化數(shù)據(jù)分析圖 本節(jié)主要介紹常用圖表的繪制,主要包括箱形圖,3D柱形圖,3D曲面圖。 ·箱形圖又稱箱線圖、盒須圖或盒式圖 ·用于顯示一組數(shù)據(jù)分散情況的統(tǒng)計圖 ·優(yōu)點(diǎn):不受異常值的影響,可以以一種相對穩(wěn)定的方式描述數(shù)據(jù)的離散分布情況,也常用于異常值

    2024年02月03日
    瀏覽(40)
  • excel兩列數(shù)據(jù)繪制單折線圖表

    excel兩列數(shù)據(jù)繪制單折線圖表

    有關(guān)excel的兩列數(shù)據(jù)繪制出一張折線圖或柱狀圖的方法。要求兩列數(shù)據(jù)分別成為圖表的橫坐標(biāo)和縱坐標(biāo)。 首先,打開excel軟件,輸入數(shù)據(jù)(以下為范例,大家根據(jù)實(shí)際輸入) 接著 選中將作為圖表縱坐標(biāo)的數(shù)據(jù)。 選擇插入圖表,選擇折線圖。 軟件自動生成了圖表。 可以發(fā)現(xiàn),

    2024年02月16日
    瀏覽(20)
  • 數(shù)據(jù)可視化(七)常用圖表的繪制

    數(shù)據(jù)可視化(七)常用圖表的繪制

    1. 2. ? 3. ? 4. ? ? ? ? ? ? ?

    2024年02月14日
    瀏覽(43)
  • 用Python繪制六種可視化圖表,簡直太好用了

    用Python繪制六種可視化圖表,簡直太好用了

    前言 嗨嘍~大家好呀,這里是魔王吶 ? ~! python資料、源碼、教程: 點(diǎn)擊此處跳轉(zhuǎn)文末名片獲取 可視化圖表,有相當(dāng)多種,但常見的也就下面幾種,其他比較復(fù)雜一點(diǎn),大都也是基于如下幾種進(jìn)行組合,變換出來的。 對于初學(xué)者來說,很容易被這官網(wǎng)上眾多的圖表類型給嚇著

    2024年02月10日
    瀏覽(99)
  • pyecharts繪制各種數(shù)據(jù)可視化圖表案例(效果+代碼)

    pyecharts繪制各種數(shù)據(jù)可視化圖表案例(效果+代碼)

    1、pyecharts繪制餅圖(顯示百分比) 2、pyecharts繪制柱狀圖 3、pyecharts繪制折線圖 4、pyecharts繪制柱形折線組合圖 5、pyecharts繪制散點(diǎn)圖 6、pyecharts繪制玫瑰圖 7、pyecharts繪制詞云圖 8、pyecharts繪制雷達(dá)圖 9、pyecharts繪制散點(diǎn)圖 10、pyecharts繪制嵌套餅圖 11、pyecharts繪制中國地圖 12、

    2024年02月09日
    瀏覽(31)
  • Matplotlib可視化數(shù)據(jù)分析圖表下(常用圖表的繪制、折線圖、柱形圖、直方圖、餅形圖、散點(diǎn)圖、面積圖、熱力圖、箱形圖、3D圖表、繪制多個圖表、雙y軸可視化圖表、顏色漸變圖)

    Matplotlib可視化數(shù)據(jù)分析圖表下(常用圖表的繪制、折線圖、柱形圖、直方圖、餅形圖、散點(diǎn)圖、面積圖、熱力圖、箱形圖、3D圖表、繪制多個圖表、雙y軸可視化圖表、顏色漸變圖)

    本文來自《Python數(shù)據(jù)分析從入門到精通》_明日科技編著 本節(jié)介紹常用圖表的繪制,主要包括繪制折線圖、繪制柱形圖、繪制直方圖、繪制餅形圖、繪制散點(diǎn)圖、繪制面積圖、繪制熱力圖、繪制箱型圖、繪制3D圖表、繪制多個子圖表以及圖表的保存。對于常用的圖表類型以繪制

    2023年04月23日
    瀏覽(42)
  • python日常記賬本源代碼,基于PySide6,支持快速查詢、繪制圖表

    python日常記賬本源代碼,基于PySide6,支持快速查詢、繪制圖表

    python日常記賬本源代碼,基于PySide6(Qt for Python 6)的賬本,界面簡潔、功能強(qiáng)大,支持保存文件、快速查詢、繪制圖表等,是平時記賬的不錯選擇。賬目查詢、賬本編輯、添加/刪除、撤銷/重做、統(tǒng)計數(shù)據(jù)、生成圖表。 運(yùn)行截圖: 完整程序下載地址:python日常記賬本源代碼

    2024年02月11日
    瀏覽(43)
  • Python可視化神器:pyecharts,輕松繪制 30+ 種超實(shí)用精美圖表!

    Python可視化神器:pyecharts,輕松繪制 30+ 種超實(shí)用精美圖表!

    歡迎關(guān)注 ,專注 Python、數(shù)據(jù)分析、數(shù)據(jù)挖掘、好玩工具! 如果要問:Python 中有那些可視化工具庫?我想很多人都能想起來 matplotlib,這是一款初學(xué)者繞不開的庫,但隨著對數(shù)據(jù)可視化的要求越來越高,matplotlib 已無法滿足了。 今天我將和大家詳細(xì)講解 Pyecharts 模塊,說到它

    2023年04月08日
    瀏覽(28)
  • Streamlit 講解專欄(十二):數(shù)據(jù)可視化-圖表繪制詳解(下)

    Streamlit 講解專欄(十二):數(shù)據(jù)可視化-圖表繪制詳解(下)

    數(shù)據(jù)可視化在數(shù)據(jù)分析和數(shù)據(jù)科學(xué)領(lǐng)域中扮演著至關(guān)重要的角色。通過可視化數(shù)據(jù),我們能夠更好地理解其背后的模式和趨勢,從而作出準(zhǔn)確的決策和預(yù)測。然而,要將原始數(shù)據(jù)轉(zhuǎn)化為有意義的圖表并不容易。這就是為什么我們需要強(qiáng)大而靈活的工具來幫助我們實(shí)現(xiàn)這一目標(biāo)

    2024年02月09日
    瀏覽(38)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包