Python使用Matplotlib繪制基礎(chǔ)可視化圖表的完整指南
在Python中進(jìn)行數(shù)據(jù)可視化,最常用且功能強(qiáng)大的庫是 Matplotlib。它可以幫助你輕松繪制出柱狀圖、折線圖、餅圖、散點(diǎn)圖、直方圖、箱線圖、熱力圖、雷達(dá)圖等。
在開始之前,請確保你已經(jīng)安裝了Matplotlib庫。如果沒有,可以在終端或命令行中運(yùn)行以下命令進(jìn)行安裝:
pip install matplotlib
1.折線圖 (Line Chart)
折線圖非常適合展示數(shù)據(jù)隨時間變化的趨勢。
import matplotlib.pyplot as plt
# 解決中文顯示問題 (Windows系統(tǒng)使用SimHei,Mac系統(tǒng)可換成PingFang SC)
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 準(zhǔn)備數(shù)據(jù)
months = ["1月", "2月", "3月", "4月", "5月", "6月"]
sales =[78,85,74,95,84,80]
# 繪制折線圖
plt.figure(figsize=(8, 5)) # 設(shè)置畫布大小
plt.plot(months, sales, marker="o", color="blue", linewidth=2, label="銷售額")
# 添加標(biāo)題和標(biāo)簽
plt.title("上半年銷售額趨勢")
plt.xlabel("月份")
plt.ylabel("銷售額(元)")
plt.legend() # 顯示圖例
plt.grid(True, linestyle="--", alpha=0.5) # 添加網(wǎng)格線
plt.show()效果圖:

2.柱狀圖 (Bar Chart)
柱狀圖適合比較不同類別之間的數(shù)值大小。
import matplotlib.pyplot as plt
# 解決中文顯示問題
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 準(zhǔn)備數(shù)據(jù)
products = ["手機(jī)", "電腦", "耳機(jī)", "平板", "手表"]
sales =[78,85,74,95,84]
# 繪制柱狀圖
plt.figure(figsize=(8, 5))
plt.bar(products, sales, color="orange", width=0.6)
# 在柱子頂部添加具體的數(shù)值標(biāo)簽
for index, value in enumerate(sales):
plt.text(index, value + 10, str(value), ha="center")
# 添加標(biāo)題和標(biāo)簽
plt.title("不同產(chǎn)品銷量對比")
plt.xlabel("產(chǎn)品")
plt.ylabel("銷量")
plt.show()效果圖:

3.餅圖 (Pie Chart)
餅圖主要用于展示各部分?jǐn)?shù)據(jù)在整體中的占比關(guān)系。
import matplotlib.pyplot as plt
# 解決中文顯示問題
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 準(zhǔn)備數(shù)據(jù)
channels = ["搜索引擎", "短視頻", "社交媒體", "直接訪問", "郵件"]
users =[1000, 500, 300, 400, 200]
# 繪制餅圖
plt.figure(figsize=(7, 7))
plt.pie(
users,
labels=channels,
autopct="%.1f%%", # 顯示百分比,并保留1位小數(shù)
startangle=90, # 設(shè)置餅圖起始角度
counterclock=False # 按順時針方向繪制
)
plt.title("用戶來源占比")
plt.show()效果圖

4.散點(diǎn)圖 (Scatter Plot)
測試數(shù)據(jù):模擬了100名學(xué)生的“每日學(xué)習(xí)時長”與“期末考試成績”之間的關(guān)系,用來觀察兩者是否存在正相關(guān)。
import matplotlib.pyplot as plt
import numpy as np
# 設(shè)置中文顯示
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 生成測試數(shù)據(jù):100個學(xué)生的學(xué)習(xí)時長(1-8小時)和對應(yīng)的成績
np.random.seed(42) # 固定隨機(jī)種子,保證每次運(yùn)行結(jié)果一致
study_hours = np.random.uniform(1, 8, 100)
# 成績 = 學(xué)習(xí)時長 * 8 + 基礎(chǔ)分40 + 隨機(jī)波動
scores = study_hours * 8 + 40 + np.random.normal(0, 5, 100)
# 繪制散點(diǎn)圖
plt.figure(figsize=(8, 5))
plt.scatter(study_hours, scores, color="skyblue", edgecolors="black", alpha=0.7)
plt.title("學(xué)習(xí)時長與考試成績的關(guān)系", fontsize=14)
plt.xlabel("每日學(xué)習(xí)時長 (小時)")
plt.ylabel("考試成績 (分)")
plt.grid(True, linestyle="--", alpha=0.5)
plt.show()效果圖

5.直方圖 (Histogram)
測試數(shù)據(jù):模擬了1000名成年男性的身高數(shù)據(jù)(符合正態(tài)分布),用來展示身高的整體分布區(qū)間。
import matplotlib.pyplot as plt
import numpy as np
# 設(shè)置中文顯示
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 生成測試數(shù)據(jù):1000名男性的身高 (均值175cm,標(biāo)準(zhǔn)差7cm)
np.random.seed(42)
heights = np.random.normal(175, 7, 1000)
# 繪制直方圖
plt.figure(figsize=(8, 5))
# bins=30 表示將數(shù)據(jù)分成30個區(qū)間,color設(shè)置顏色,edgecolor設(shè)置柱子邊框色
plt.hist(heights, bins=30, color="mediumseagreen", edgecolor="black", alpha=0.7)
plt.title("成年男性身高分布情況", fontsize=14)
plt.xlabel("身高 (cm)")
plt.ylabel("人數(shù)")
plt.grid(axis="y", linestyle="--", alpha=0.5)
plt.show()效果圖

6.箱線圖 (Box Plot)
測試數(shù)據(jù):模擬了 A、B、C 三個不同班級學(xué)生的數(shù)學(xué)成績,用來對比各班的平均水平、波動范圍以及識別異常低分/高分。
import matplotlib.pyplot as plt
import numpy as np
# 設(shè)置中文顯示
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 生成測試數(shù)據(jù):三個班級的數(shù)學(xué)成績
np.random.seed(42)
class_A = np.random.normal(75, 10, 100) # A班:均值75,標(biāo)準(zhǔn)差10
class_B = np.random.normal(80, 8, 100) # B班:均值80,標(biāo)準(zhǔn)差8
class_C = np.random.normal(70, 12, 100) # C班:均值70,標(biāo)準(zhǔn)差12(波動更大)
# 將數(shù)據(jù)組合成列表傳入
data_to_plot = [class_A, class_B, class_C]
labels = ["A班", "B班", "C班"]
# 繪制箱線圖
plt.figure(figsize=(8, 5))
plt.boxplot(data_to_plot, labels=labels, patch_artist=True,
boxprops=dict(facecolor="lightcoral", color="black"),
medianprops=dict(color="white"))
plt.title("三個班級數(shù)學(xué)成績分布對比", fontsize=14)
plt.ylabel("數(shù)學(xué)成績")
plt.grid(axis="y", linestyle="--", alpha=0.5)
plt.show()效果圖

7.熱力圖 (Heatmap)
繪制熱力圖我們需要用到更美觀的 seaborn 庫。請先在終端或命令行中運(yùn)行以下命令安裝依賴:
pip install matplotlib seaborn numpy pandas
測試數(shù)據(jù):模擬了一周7天內(nèi),某電商平臺在24小時內(nèi)的每小時訂單量矩陣,用來直觀查看哪個時間段是下單高峰期。
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
# 設(shè)置中文顯示
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 生成測試數(shù)據(jù):7天 x 24小時的訂單量矩陣
np.random.seed(42)
days = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
hours = [f"{h}點(diǎn)" for h in range(24)]
# 模擬數(shù)據(jù):周末和晚間訂單量較高
orders = np.random.randint(10, 100, size=(7, 24))
orders[5:, 18:23] += 50 # 周末晚間增加訂單量
# 將數(shù)據(jù)轉(zhuǎn)換為 DataFrame
df = pd.DataFrame(orders, index=days, columns=hours)
# 繪制熱力圖
plt.figure(figsize=(14, 6))
# annot=True 顯示數(shù)值,fmt="d" 表示顯示為整數(shù),cmap 設(shè)置顏色主題
sns.heatmap(df, annot=False, fmt="d", cmap="YlOrRd", cbar_kws={'label': '訂單量'})
plt.title("一周內(nèi)每小時訂單量熱力圖", fontsize=14)
plt.xlabel("時間")
plt.ylabel("星期")
plt.show()效果圖

8.雷達(dá)圖(radar chart)
雷達(dá)圖(也叫蜘蛛圖)非常適合用來展示多維度的數(shù)據(jù),比如評估一個人的綜合能力、對比不同產(chǎn)品的性能指標(biāo)等。
在 Python 中,我們可以使用 matplotlib 的極坐標(biāo)系(polar coordinates)來繪制。以下是包含完整測試數(shù)據(jù)的可運(yùn)行實(shí)例,模擬了兩名游戲角色的六維能力對比
import matplotlib.pyplot as plt
import numpy as np
# 設(shè)置中文顯示 (Windows系統(tǒng)使用SimHei,Mac系統(tǒng)可換成PingFang SC)
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 1. 準(zhǔn)備測試數(shù)據(jù)
# 設(shè)定6個能力維度
categories = ["攻擊", "防御", "速度", "耐力", "技術(shù)", "策略"]
num_vars = len(categories)
# 角色A的能力值(假設(shè)是均衡型戰(zhàn)士)
stats_A = [85, 90, 70, 88, 75, 80]
# 角色B的能力值(假設(shè)是高攻高速刺客)
stats_B = [95, 60, 92, 65, 88, 70]
# 2. 計算每個維度的角度
# 將圓周(2*pi)平均分成 N 份
angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
# 3. 閉合圖形
# 雷達(dá)圖需要首尾相連,所以要把第一個維度的角度和數(shù)據(jù)追加到列表末尾
stats_A += stats_A[:1]
stats_B += stats_B[:1]
angles += angles[:1]
# 4. 創(chuàng)建極坐標(biāo)畫布并繪圖
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))
# 繪制角色A的折線和填充區(qū)域
ax.plot(angles, stats_A, color="blue", linewidth=2, linestyle="solid", label="角色 A (均衡型)")
ax.fill(angles, stats_A, color="blue", alpha=0.2)
# 繪制角色B的折線和填充區(qū)域
ax.plot(angles, stats_B, color="red", linewidth=2, linestyle="solid", label="角色 B (刺客型)")
ax.fill(angles, stats_B, color="red", alpha=0.2)
# 5. 美化圖表
# 設(shè)置半徑(能力值)的范圍,留出一點(diǎn)空間給圖例
ax.set_ylim(0, 100)
# 設(shè)置維度標(biāo)簽(攻擊、防御等)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories, size=12)
# 添加圖例
plt.legend(loc="upper right", bbox_to_anchor=(1.3, 1.1))
# 添加標(biāo)題
plt.title("游戲角色六維能力對比雷達(dá)圖", size=16, pad=20)
plt.show()效果圖

以上就是Python使用Matplotlib繪制基礎(chǔ)可視化圖表的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Python Matplotlib繪制可視化圖表的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)的NN神經(jīng)網(wǎng)絡(luò)算法完整示例
這篇文章主要介紹了Python實(shí)現(xiàn)的NN神經(jīng)網(wǎng)絡(luò)算法,結(jié)合完整實(shí)例形式分析了Python使用numpy、matplotlib及sklearn模塊實(shí)現(xiàn)NN神經(jīng)網(wǎng)絡(luò)相關(guān)算法實(shí)現(xiàn)技巧與操作注意事項(xiàng),需要的朋友可以參考下2018-06-06
python+adb+monkey實(shí)現(xiàn)Rom穩(wěn)定性測試詳解
這篇文章主要介紹了python+adb+monkey實(shí)現(xiàn)Rom穩(wěn)定性測試詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Keras 加載已經(jīng)訓(xùn)練好的模型進(jìn)行預(yù)測操作
這篇文章主要介紹了Keras 加載已經(jīng)訓(xùn)練好的模型進(jìn)行預(yù)測操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python讀取配置文件-ConfigParser的二次封裝方法
這篇文章主要介紹了Python讀取配置文件-ConfigParser的二次封裝方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
用Python將IP地址在整型和字符串之間輕松轉(zhuǎn)換
這篇文章主要給大家介紹了利用Python將IP在整型和字符串之間輕松轉(zhuǎn)換的相關(guān)資料,文中還跟大家分享了Python下利用正則表達(dá)式來匹配校驗(yàn)一個字符串是否為ip地址的方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-03-03

