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

Python數(shù)據(jù)可視化之Pandas、Matplotlib與Seaborn的高效實(shí)戰(zhàn)指南

 更新時間:2026年02月24日 08:49:25   作者:豆本-豆豆奶  
本文介紹了Python數(shù)據(jù)可視化的綜合解決方案,涵蓋Pandas、Matplotlib和Seaborn三大工具的使用技巧,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

使用Pandas內(nèi)置的繪圖功能  

Pandas基于Matplotlib封裝了便捷的繪圖接口,使數(shù)據(jù)可視化變得異常簡單。.plot()方法能夠智能識別DataFrame結(jié)構(gòu)并生成合適的圖表。

基礎(chǔ)繪圖功能

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 創(chuàng)建示例數(shù)據(jù)
np.random.seed(42)
df = pd.DataFrame({
    '銷售額': np.random.randint(100, 500, 12).cumsum(),
    '利潤': np.random.randint(20, 80, 12).cumsum()
}, index=pd.date_range('2023-01-01', periods=12, freq='M'))

# 基本折線圖
df.plot(title='2023年月度業(yè)績趨勢', 
       figsize=(10, 6),
       style=['-o', '--s'],  # 線條樣式
       linewidth=2,
       markersize=8)
plt.ylabel('金額(萬元)')
plt.grid(True, alpha=0.3)
plt.show()

多種圖表類型

# 柱狀圖
df.plot.bar(title='2023年月度業(yè)績對比', 
            figsize=(10, 6),
            color=['#3498db', '#2ecc71'],  # 自定義顏色
            alpha=0.8,
            rot=45)  # x軸標(biāo)簽旋轉(zhuǎn)角度
plt.ylabel('金額(萬元)')
plt.grid(axis='y', alpha=0.3)
plt.show()

# 面積圖
df.plot.area(title='2023年月度業(yè)績構(gòu)成', 
             figsize=(10, 6),
             alpha=0.4,
             stacked=False)  # 非堆疊模式
plt.ylabel('金額(萬元)')
plt.grid(True, alpha=0.3)
plt.show()

專業(yè)技巧

# 多子圖繪制
axes = df.plot(subplots=True, 
               figsize=(10, 8),
               layout=(2, 1),
               sharex=True,
               title=['銷售額趨勢', '利潤趨勢'],
               style=['-o', '--s'])
plt.tight_layout()
plt.show()

# 箱線圖(自動按列繪制)
df.plot.box(title='業(yè)績分布分析',
            figsize=(8, 6),
            vert=False,  # 水平箱線圖
            patch_artist=True)  # 填充顏色
plt.xlabel('金額(萬元)')
plt.show()

與Matplotlib結(jié)合進(jìn)行高級繪圖  

雖然Pandas繪圖便捷,但結(jié)合Matplotlib可以實(shí)現(xiàn)更精細(xì)的控制和更專業(yè)的可視化效果。

雙坐標(biāo)軸圖表

fig, ax1 = plt.subplots(figsize=(10, 6))

# 第一個y軸(銷售額)
color = '#3498db'
ax1.set_xlabel('月份')
ax1.set_ylabel('銷售額(萬元)', color=color)
ax1.plot(df.index, df['銷售額'], color=color, marker='o')
ax1.tick_params(axis='y', labelcolor=color)
ax1.grid(True, alpha=0.3)

# 第二個y軸(利潤率)
ax2 = ax1.twinx()
color = '#e74c3c'
ax2.set_ylabel('利潤率(%)', color=color)
# 計算利潤率(示例)
profit_rate = (df['利潤']/df['銷售額']*100).values
ax2.plot(df.index, profit_rate, color=color, marker='s', linestyle='--')
ax2.tick_params(axis='y', labelcolor=color)

plt.title('2023年銷售額與利潤率趨勢', pad=20)
fig.tight_layout()
plt.show()

專業(yè)金融圖表

from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mdates

# 準(zhǔn)備股票數(shù)據(jù)
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=20)
open_prices = np.random.normal(100, 5, 20).cumsum()
high_prices = open_prices + np.random.uniform(1, 3, 20)
low_prices = open_prices - np.random.uniform(1, 3, 20)
close_prices = open_prices + np.random.normal(0, 1, 20)

# 轉(zhuǎn)換為OHLC格式
data = pd.DataFrame({
    'Open': open_prices,
    'High': high_prices,
    'Low': low_prices,
    'Close': close_prices
}, index=dates)

# 創(chuàng)建專業(yè)K線圖
fig, ax = plt.subplots(figsize=(12, 6))

# 轉(zhuǎn)換日期格式
data['Date'] = mdates.date2num(data.index.to_pydatetime())
ohlc = data[['Date', 'Open', 'High', 'Low', 'Close']].values

# 繪制K線
candlestick_ohlc(ax, ohlc, width=0.6, 
                 colorup='r', colordown='g', alpha=0.8)

# 添加移動平均線
data['MA5'] = data['Close'].rolling(5).mean()
ax.plot(data['Date'], data['MA5'], 'b-', label='5日均線')

# 圖表裝飾
ax.xaxis_date()  # 將x軸轉(zhuǎn)換為日期格式
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
plt.xticks(rotation=45)
plt.title('股票K線圖示例', fontsize=14)
plt.ylabel('價格(元)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

與Seaborn結(jié)合進(jìn)行統(tǒng)計圖形繪制  

Seaborn是基于Matplotlib的高級統(tǒng)計可視化庫,特別適合數(shù)據(jù)分布和關(guān)系分析。  

分布可視化

import seaborn as sns

# 設(shè)置Seaborn風(fēng)格
sns.set_style("whitegrid")
sns.set_palette("husl")

# 創(chuàng)建示例數(shù)據(jù)
tips = sns.load_dataset("tips")

# 分布圖(直方圖+KDE)
plt.figure(figsize=(10, 6))
sns.histplot(data=tips, x="total_bill", kde=True,
             bins=20, alpha=0.6)
plt.title('消費(fèi)金額分布', fontsize=14)
plt.xlabel('消費(fèi)金額(美元)')
plt.ylabel('頻次')
plt.show()

# 小提琴圖(展示分布密度)
plt.figure(figsize=(10, 6))
sns.violinplot(data=tips, x="day", y="total_bill",
               hue="sex", split=True,
               inner="quartile")
plt.title('不同性別每日消費(fèi)分布', fontsize=14)
plt.xlabel('星期')
plt.ylabel('消費(fèi)金額(美元)')
plt.legend(title='性別')
plt.show()

關(guān)系分析

# 散點(diǎn)圖矩陣
sns.pairplot(tips, hue="time", 
             palette="Set2",
             height=2.5,
             corner=True)  # 只顯示下三角
plt.suptitle('消費(fèi)數(shù)據(jù)關(guān)系矩陣', y=1.02)
plt.show()

# 熱力圖(相關(guān)性分析)
plt.figure(figsize=(8, 6))
corr = tips.corr(numeric_only=True)
sns.heatmap(corr, annot=True, fmt=".2f",
            cmap="coolwarm",
            linewidths=.5,
            cbar_kws={'label': '相關(guān)系數(shù)'})
plt.title('消費(fèi)數(shù)據(jù)相關(guān)性分析', fontsize=14)
plt.xticks(rotation=45)
plt.yticks(rotation=0)
plt.show()

高級統(tǒng)計圖表

# 回歸分析圖
plt.figure(figsize=(10, 6))
sns.regplot(data=tips, x="total_bill", y="tip",
            scatter_kws={'alpha':0.5},
            line_kws={'color':'red'})
plt.title('消費(fèi)金額與小費(fèi)金額關(guān)系', fontsize=14)
plt.xlabel('消費(fèi)金額(美元)')
plt.ylabel('小費(fèi)金額(美元)')
plt.grid(True, alpha=0.3)
plt.show()

# 分面網(wǎng)格(FacetGrid)
g = sns.FacetGrid(tips, col="time", row="smoker",
                  margin_titles=True,
                  height=4)
g.map(sns.scatterplot, "total_bill", "tip", alpha=0.7)
g.fig.suptitle('不同場景下消費(fèi)金額與小費(fèi)關(guān)系', y=1.03)
plt.tight_layout()
plt.show()

三庫結(jié)合的綜合案例

# 創(chuàng)建綜合可視化面板
plt.figure(figsize=(16, 12))

# 子圖1:Pandas折線圖
plt.subplot(2, 2, 1)
df.plot(ax=plt.gca(), style=['-o', '--s'], linewidth=2)
plt.title('Pandas折線圖')
plt.grid(True, alpha=0.3)

# 子圖2:Matplotlib高級圖表
plt.subplot(2, 2, 2)
ax1 = plt.gca()
ax1.plot(df.index, df['銷售額'], 'b-o', label='銷售額')
ax1.set_ylabel('銷售額(萬元)', color='b')
ax1.tick_params(axis='y', labelcolor='b')
ax1.grid(True, alpha=0.3)

ax2 = ax1.twinx()
ax2.plot(df.index, profit_rate, 'r--s', label='利潤率')
ax2.set_ylabel('利潤率(%)', color='r')
ax2.tick_params(axis='y', labelcolor='r')
plt.title('Matplotlib雙坐標(biāo)軸圖')
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')

# 子圖3:Seaborn分布圖
plt.subplot(2, 2, 3)
sns.violinplot(data=tips, x="day", y="total_bill", hue="sex", split=True)
plt.title('Seaborn小提琴圖')
plt.legend(title='性別')

# 子圖4:Seaborn關(guān)系圖
plt.subplot(2, 2, 4)
sns.scatterplot(data=tips, x="total_bill", y="tip", 
               hue="time", style="sex", size="size",
               sizes=(20, 200), alpha=0.7)
plt.title('Seaborn多維度散點(diǎn)圖')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

plt.tight_layout()
plt.show()

專業(yè)建議與最佳實(shí)踐  

工具選擇原則

快速探索:優(yōu)先使用Pandas內(nèi)置繪圖 

統(tǒng)計可視化:首選Seaborn 

高度定制化:使用Matplotlib底層API 

性能優(yōu)化

# 大數(shù)據(jù)集優(yōu)化
plt.plot(large_data.index, large_data.values, '-', rasterized=True)

樣式統(tǒng)一

# 全局樣式設(shè)置
plt.style.use('seaborn')
plt.rcParams.update({
    'font.size': 12,
    'axes.titlesize': 14,
    'axes.labelsize': 12
})

交互式可視化

# 啟用交互模式
plt.ion()
# 繪制圖表后保持交互
plt.show(block=True)

輸出專業(yè)報告

# 保存高質(zhì)量圖片
plt.savefig('professional_plot.png', 
           dpi=300, 
           bbox_inches='tight',
           transparent=True)

通過掌握Pandas、Matplotlib和Seaborn這三大可視化工具的組合使用,我們就能夠高效地從數(shù)據(jù)探索過渡到專業(yè)報告制作,滿足不同場景下的數(shù)據(jù)可視化需求。

到此這篇關(guān)于Python數(shù)據(jù)可視化之Pandas、Matplotlib與Seaborn的高效實(shí)戰(zhàn)指南的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)可視化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python實(shí)現(xiàn)中文文本分句的例子

    python實(shí)現(xiàn)中文文本分句的例子

    今天小編就為大家分享一篇python實(shí)現(xiàn)中文文本分句的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • matplotlib如何設(shè)置坐標(biāo)軸刻度的個數(shù)及標(biāo)簽的方法總結(jié)

    matplotlib如何設(shè)置坐標(biāo)軸刻度的個數(shù)及標(biāo)簽的方法總結(jié)

    這里介紹兩種設(shè)置坐標(biāo)軸刻度的方法,一種是利用pyplot提交的api去進(jìn)行設(shè)置,另一種是通過調(diào)用面向?qū)ο蟮腶pi, 即通過matplotlib.axes.Axes去設(shè)置,需要的朋友可以參考下
    2021-06-06
  • pytorch 實(shí)現(xiàn)多個Dataloader同時訓(xùn)練

    pytorch 實(shí)現(xiàn)多個Dataloader同時訓(xùn)練

    這篇文章主要介紹了pytorch 實(shí)現(xiàn)多個Dataloader同時訓(xùn)練的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python如何快速提取PowerPoint文檔中的圖片

    Python如何快速提取PowerPoint文檔中的圖片

    這篇文章主要為大家通過兩個示例詳細(xì)介紹一下如何使用Python提取PPT文檔中的圖片,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下
    2024-10-10
  • Python?的?ultralytics?庫功能及安裝方法

    Python?的?ultralytics?庫功能及安裝方法

    ultralytics庫由Ultralytics團(tuán)隊開發(fā),旨在為YOLO系列模型提供高效、靈活且易于使用的工具,本文將詳細(xì)介紹ultralytics庫的功能、安裝方法、核心模塊以及使用示例,感興趣的朋友一起看看吧
    2025-03-03
  • python函數(shù)的作用域及關(guān)鍵字詳解

    python函數(shù)的作用域及關(guān)鍵字詳解

    這篇文章主要介紹了python函數(shù)的作用域及關(guān)鍵字詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Python進(jìn)階Matplotlib庫圖繪制

    Python進(jìn)階Matplotlib庫圖繪制

    這篇文章主要介紹了Python進(jìn)階Matplotlib庫圖繪制,Matplotlib:是一個Python的2D繪圖庫,通過Matplotlib,開發(fā)者可以僅需要幾行代碼,便可以生成折線圖,直方圖,條形圖,餅狀圖,散點(diǎn)圖等
    2022-07-07
  • 在Linux命令行終端中使用python的簡單方法(推薦)

    在Linux命令行終端中使用python的簡單方法(推薦)

    下面小編就為大家?guī)硪黄贚inux命令行終端中使用python的簡單方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • 簡潔的十分鐘Python入門教程

    簡潔的十分鐘Python入門教程

    這篇文章主要介紹了簡潔的十分鐘Python入門教程,Python語言本身的簡潔也使得網(wǎng)絡(luò)上各種Python快門入門教程有著很高的人氣,本文是國內(nèi)此類其中的一篇,需要的朋友可以參考下
    2015-04-04
  • python實(shí)現(xiàn)Zabbix-API監(jiān)控

    python實(shí)現(xiàn)Zabbix-API監(jiān)控

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)Zabbix-API監(jiān)控,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09

最新評論

思南县| 迁安市| 安远县| 宝山区| 句容市| 延吉市| 葫芦岛市| 汉源县| 玛纳斯县| 武宁县| 江津市| 汝阳县| 滁州市| 博罗县| 灵寿县| 鹰潭市| 汉中市| 巴塘县| 沧州市| 九江县| 通山县| 华安县| 宝丰县| 清水河县| 永德县| 乐都县| 婺源县| 什邡市| 望城县| 正定县| 吴川市| 泽州县| 宁河县| 永德县| 新丰县| 益阳市| 旅游| 巴楚县| 湾仔区| 精河县| 南通市|