Share via


以 Python 繪製長條圖

適用於:SQL ServerAzure SQL DatabaseAzure SQL 受控執行個體

本文描述如何使用 Python 套件 pandas'.hist() 來繪製資料。 SQL 資料庫是用來將具有非重疊連續值的長條圖資料間隔視覺化的來源。

必要條件

驗證還原的資料庫

您可透過查詢 Person.CountryRegion 資料表驗證還原的資料庫是否存在:

USE AdventureWorksDW;
SELECT * FROM Person.CountryRegion;

安裝 Python 套件

下載及安裝 Azure Data Studio

安裝下列 Python 套件:

  • pyodbc
  • pandas
  • sqlalchemy
  • matplotlib

若要安裝這些套件:

  1. 在 Azure Data Studio 筆記本中,選取 [管理套件]。
  2. 在 [管理套件] 窗格中,選取 [新增] 索引標籤。
  3. 針對下列每個封裝,輸入封裝名稱,選取 [搜尋],然後選取 [安裝]。

繪製長條圖

長條圖中顯示的分散式資料是以 AdventureWorksDW2022 的 SQL 查詢為基礎。 長條圖會將資料及資料值的頻率視覺化。

編輯連接字串變數 'server'、'database'、'username' 和 'password' 以連線到 SQL Server 資料庫。

建立新的筆記本:

  1. 在 Azure Data Studio 中,選取 [檔案],然後選取 [新增筆記本]。
  2. 在筆記本中,選取核心 [Python3],然後選取 [+程式碼]。
  3. 將程式碼貼到筆記本中,然後選取 [全部執行]。
import pyodbc 
import pandas as pd
import matplotlib
import sqlalchemy

from sqlalchemy import create_engine

matplotlib.use('TkAgg', force=True)
from matplotlib import pyplot as plt

# Some other example server values are
# server = 'localhost\sqlexpress' # for a named instance
# server = 'myserver,port' # to specify an alternate port
server = 'servername'
database = 'AdventureWorksDW2022'
username = 'yourusername'
password = 'databasename'

url = 'mssql+pyodbc://{user}:{passwd}@{host}:{port}/{db}?driver=SQL+Server'.format(user=username, passwd=password, host=server, port=port, db=database)
engine = create_engine(url)

sql = "SELECT DATEDIFF(year, c.BirthDate, GETDATE()) AS Age FROM [dbo].[FactInternetSales] s INNER JOIN dbo.DimCustomer c ON s.CustomerKey = c.CustomerKey"

df = pd.read_sql(sql, engine)
df.hist(bins=50)

plt.show()

顯示畫面會顯示 FactInternetSales 資料表中客戶的年齡分佈。

Diagram showing the Pandas histogram distribution.