JupyterLab 預設介面是英文,對初學者不夠友善。
使用 matplotlib 繪製圖表時,中文標題和標籤會顯示成方塊 (□□□)。
程式輸出的中文可能出現編碼錯誤。
💡 本課程目標
完整解決以上三個問題,讓您的 Jupyter 環境完美支援中文!
| 特性 | Jupyter Notebook (舊版) | JupyterLab (新版) |
|---|---|---|
| 介面中文化 | ❌ 不支援 | ✅ 完整支援 |
| 多檔案管理 | ❌ 單檔案 | ✅ 分頁管理 |
| 擴充功能 | ⚠️ 有限 | ✅ 豐富 |
| 終端機整合 | ⚠️ 基本 | ✅ 完整 |
| 適合對象 | 簡單教學 | 專業開發 |
🎯 建議
本課程將教您安裝 JupyterLab,因為它支援完整的介面中文化,功能更強大!
Windows: 按 Win + R,輸入 cmd
macOS/Linux: 開啟 Terminal
python -m pip install --upgrade pip
pip install jupyterlab
這會同時安裝 Jupyter Notebook 和 JupyterLab
jupyter --version
應該顯示版本資訊
ℹ️ 安裝時間: 通常需要 2-5 分鐘,取決於網路速度
您的環境沒有「中文語系」選項的原因:
因為您的 JupyterLab 沒有安裝「中文語言包」
💡 現在的狀態
您現在看到只有 English,就是標準的「未安裝語言包狀態」。
接下來我們會教您如何安裝!
JupyterLab 從 v3 開始支援語言包,但您要自己安裝。
在 JupyterLab 中: File → New → Terminal
或使用系統的終端機 (cmd / Terminal)
pip install jupyterlab-language-pack-zh-TW
或安裝簡體中文:
pip install jupyterlab-language-pack-zh-CN
關閉整個 JupyterLab 視窗
在終端機按 Ctrl + C 停止
然後重新執行: jupyter lab
✅ 安裝完成! 現在可以切換語言了
點選上方選單: Settings → Language
現在您會看到:
Chinese (Traditional) - 繁體中文Chinese (Simplified) - 簡體中文選擇您想要的語言
按 F5 或重新整理瀏覽器
🎉 完成! 介面選單、按鈕、設定視窗都會變成中文
Windows 已內建中文字型,可直接使用:
Microsoft JhengHei - 微軟正黑體Microsoft YaHei - 微軟雅黑SimHei - 黑體macOS 已內建中文字型:
PingFang TC - 蘋方-繁Heiti TC - 黑體-繁# Ubuntu / Debian sudo apt update sudo apt install fonts-noto fonts-noto-cjk # CentOS / RHEL sudo yum install google-noto-cjk-fonts
安裝後可使用:
Noto Sans CJK TC - 思源黑體Noto Serif CJK TC - 思源宋體✅ 安裝完成後,重新啟動 JupyterLab 即可使用
# 在終端機或 JupyterLab Terminal 執行
pip install matplotlib
在每個需要繪圖的 Notebook 開頭加入:
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt # Windows 使用者 plt.rcParams["font.family"] = "Microsoft JhengHei" # macOS 使用者 # plt.rcParams["font.family"] = "PingFang TC" # Linux 使用者 # plt.rcParams["font.family"] = "Noto Sans CJK TC" # 解決負號顯示問題 plt.rcParams["axes.unicode_minus"] = False
plt.title("這是中文標題") plt.xlabel("X 軸標籤") plt.ylabel("Y 軸標籤") plt.plot([1, 2, 3], [3, 2, 5]) plt.show()
✅ 如果中文正常顯示,設定成功!
在 Jupyter Notebook 中執行:
import matplotlib print(matplotlib.matplotlib_fname())
會顯示設定檔路徑,例如:
C:\Users\YourName\.matplotlib\matplotlibrc
如果檔案不存在,建立一個新的 matplotlibrc 檔案
# Windows font.family : Microsoft JhengHei # macOS # font.family : PingFang TC # Linux # font.family : Noto Sans CJK TC # 解決負號問題 axes.unicode_minus : False
關閉並重新啟動,設定即生效
✅ 完成! 之後所有 Notebook 都會自動使用中文字型,不需要每次設定
# -*- coding: utf-8 -*- import matplotlib.font_manager as fm # 取得所有字型 fonts = fm.findSystemFonts() # 取得字型名稱 font_names = [] for font in fonts: try: font_prop = fm.FontProperties(fname=font) font_name = font_prop.get_name() font_names.append(font_name) except: pass # 移除重複並排序 font_names = sorted(set(font_names)) # 顯示所有字型 print(f"系統共有 {len(font_names)} 種字型:") for i, name in enumerate(font_names, 1): print(f"{i}. {name}")
# 篩選包含中文相關關鍵字的字型 chinese_fonts = [f for f in font_names if any(keyword in f.lower() for keyword in ['chinese', 'cjk', 'hei', 'ming', 'jhenghei', 'yahei', 'pingfang', 'noto'])] print("\n可用的中文字型:") for font in chinese_fonts: print(f" - {font}")
💡 提示: 執行後會列出所有可用字型,找到適合的中文字型名稱後,就可以在 matplotlib 中使用!
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np # 設定中文字型 plt.rcParams["font.family"] = "Microsoft JhengHei" plt.rcParams["axes.unicode_minus"] = False # 資料 subjects = ['國文', '英文', '數學', '自然', '社會'] scores = [78, 85, 72, 88, 82] # 建立圖表 plt.figure(figsize=(10, 6)) bars = plt.bar(subjects, scores, color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'], edgecolor='black', linewidth=1.5) # 在長條上方顯示數值 for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2., height, f'{height}分', ha='center', va='bottom', fontsize=12, fontweight='bold') # 設定標題和標籤 plt.title('高一甲班各科平均成績', fontsize=18, fontweight='bold', pad=20) plt.xlabel('科目', fontsize=14) plt.ylabel('平均分數', fontsize=14) # 加入參考線 plt.axhline(y=80, color='red', linestyle='--', alpha=0.7, label='目標分數 80') # 設定 Y 軸範圍 plt.ylim(0, 100) # 加入網格 plt.grid(axis='y', alpha=0.3, linestyle='--') # 顯示圖例 plt.legend() # 調整版面 plt.tight_layout() plt.show()
🎨 效果: 彩色長條圖,每個長條上方顯示分數,包含目標線!
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt # 設定中文字型 plt.rcParams["font.family"] = "Microsoft JhengHei" # 資料 categories = ['房租', '餐飲', '交通', '娛樂', '儲蓄', '其他'] amounts = [12000, 8000, 3000, 4000, 10000, 3000] # 顏色設定 colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DFE6E9'] # 突出顯示儲蓄 explode = (0, 0, 0, 0, 0.1, 0) # 建立圖表 plt.figure(figsize=(10, 8)) wedges, texts, autotexts = plt.pie(amounts, labels=categories, colors=colors, explode=explode, autopct='%1.1f%%', startangle=90, textprops={'fontsize': 12, 'fontweight': 'bold'}) # 設定百分比文字顏色 for autotext in autotexts: autotext.set_color('white') autotext.set_fontsize(11) # 標題 plt.title('每月家庭支出分配\n總支出: NT$ 40,000', fontsize=16, fontweight='bold', pad=20) # 加入圖例 plt.legend(wedges, [f'{cat}: NT$ {amt:,}' for cat, amt in zip(categories, amounts)], loc="best", fontsize=10) plt.tight_layout() plt.show()
🎨 效果: 彩色圓餅圖,自動顯示百分比,儲蓄部分突出顯示!
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np # 設定中文字型 plt.rcParams["font.family"] = "Microsoft JhengHei" plt.rcParams["axes.unicode_minus"] = False # 資料 months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'] stock_a = [150, 155, 148, 162, 170, 165, 175, 180, 172, 185, 190, 195] stock_b = [120, 125, 130, 128, 135, 140, 138, 145, 150, 148, 155, 160] # 建立圖表 plt.figure(figsize=(12, 6)) # 繪製兩條折線 plt.plot(months, stock_a, marker='o', linewidth=2.5, markersize=8, label='台積電', color='#FF6B6B') plt.plot(months, stock_b, marker='s', linewidth=2.5, markersize=8, label='鴻海', color='#4ECDC4') # 標註最高點 max_a_idx = stock_a.index(max(stock_a)) plt.annotate(f'最高: {max(stock_a)}元', xy=(max_a_idx, max(stock_a)), xytext=(max_a_idx-1, max(stock_a)+10), arrowprops=dict(arrowstyle='->', color='red'), fontsize=11, fontweight='bold') # 設定標題和標籤 plt.title('2024年股票價格走勢比較', fontsize=18, fontweight='bold', pad=20) plt.xlabel('月份', fontsize=14) plt.ylabel('股價 (元)', fontsize=14) # 加入網格 plt.grid(True, alpha=0.3, linestyle='--') # 顯示圖例 plt.legend(fontsize=12, loc='upper left') # 設定 Y 軸範圍 plt.ylim(100, 210) plt.tight_layout() plt.show()
🎨 效果: 雙線比較圖,包含標註和圖例!
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np # 設定中文字型 plt.rcParams["font.family"] = "Microsoft JhengHei" # 生成模擬資料 np.random.seed(42) heights = np.random.normal(170, 10, 50) # 身高 (cm) weights = heights * 0.6 + np.random.normal(0, 5, 50) # 體重 (kg) # 建立圖表 plt.figure(figsize=(10, 8)) # 繪製散佈圖 scatter = plt.scatter(heights, weights, c=weights, cmap='viridis', s=100, alpha=0.6, edgecolors='black', linewidth=1) # 加入趨勢線 z = np.polyfit(heights, weights, 1) p = np.poly1d(z) plt.plot(heights, p(heights), "r--", linewidth=2, label='趨勢線') # 加入顏色條 cbar = plt.colorbar(scatter) cbar.set_label('體重 (kg)', fontsize=12) # 設定標題和標籤 plt.title('身高與體重關係散佈圖', fontsize=18, fontweight='bold', pad=20) plt.xlabel('身高 (cm)', fontsize=14) plt.ylabel('體重 (kg)', fontsize=14) # 加入網格 plt.grid(True, alpha=0.3, linestyle='--') # 顯示圖例 plt.legend(fontsize=12) plt.tight_layout() plt.show()
🎨 效果: 彩色散佈圖,包含趨勢線和顏色條!
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np # 設定中文字型 plt.rcParams["font.family"] = "Microsoft JhengHei" # 科目 subjects = ['國文', '英文', '數學', '物理', '化學'] # 相關性矩陣 (模擬資料) correlation = np.array([ [1.00, 0.65, 0.45, 0.30, 0.35], [0.65, 1.00, 0.55, 0.40, 0.45], [0.45, 0.55, 1.00, 0.85, 0.80], [0.30, 0.40, 0.85, 1.00, 0.75], [0.35, 0.45, 0.80, 0.75, 1.00] ]) # 建立圖表 fig, ax = plt.subplots(figsize=(10, 8)) # 繪製熱力圖 im = ax.imshow(correlation, cmap='RdYlGn', aspect='auto', vmin=0, vmax=1) # 設定刻度 ax.set_xticks(np.arange(len(subjects))) ax.set_yticks(np.arange(len(subjects))) ax.set_xticklabels(subjects, fontsize=12) ax.set_yticklabels(subjects, fontsize=12) # 在每個格子中顯示數值 for i in range(len(subjects)): for j in range(len(subjects)): text = ax.text(j, i, f'{correlation[i, j]:.2f}', ha="center", va="center", color="black" if correlation[i, j] > 0.5 else "white", fontsize=11, fontweight='bold') # 加入顏色條 cbar = plt.colorbar(im, ax=ax) cbar.set_label('相關係數', fontsize=12) # 設定標題 ax.set_title('各科成績相關性熱力圖', fontsize=18, fontweight='bold', pad=20) plt.tight_layout() plt.show()
🎨 效果: 彩色熱力圖,數值越高顏色越綠,一眼看出科目相關性!
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np # 設定中文字型 plt.rcParams["font.family"] = "Microsoft JhengHei" plt.rcParams["axes.unicode_minus"] = False # 建立 2x2 子圖 fig, axes = plt.subplots(2, 2, figsize=(14, 10)) fig.suptitle('學生學習數據綜合分析', fontsize=20, fontweight='bold', y=0.995) # 子圖 1: 長條圖 - 各科成績 subjects = ['國文', '英文', '數學', '自然'] scores = [78, 85, 72, 88] axes[0, 0].bar(subjects, scores, color='skyblue', edgecolor='black') axes[0, 0].set_title('各科平均成績', fontsize=14, fontweight='bold') axes[0, 0].set_ylabel('分數') axes[0, 0].grid(axis='y', alpha=0.3) # 子圖 2: 圓餅圖 - 時間分配 activities = ['上課', '自習', '休息', '其他'] hours = [6, 4, 8, 6] axes[0, 1].pie(hours, labels=activities, autopct='%1.1f%%', colors=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']) axes[0, 1].set_title('每日時間分配', fontsize=14, fontweight='bold') # 子圖 3: 折線圖 - 月考成績趨勢 months = ['第1次', '第2次', '第3次', '第4次'] trend = [75, 78, 82, 85] axes[1, 0].plot(months, trend, marker='o', linewidth=2, markersize=8, color='green') axes[1, 0].set_title('月考成績進步趨勢', fontsize=14, fontweight='bold') axes[1, 0].set_ylabel('平均分數') axes[1, 0].grid(True, alpha=0.3) # 子圖 4: 散佈圖 - 讀書時間 vs 成績 study_hours = [2, 3, 4, 5, 6, 7, 8] exam_scores = [65, 70, 75, 80, 85, 88, 90] axes[1, 1].scatter(study_hours, exam_scores, s=100, c=exam_scores, cmap='viridis', edgecolors='black') axes[1, 1].set_title('讀書時間與成績關係', fontsize=14, fontweight='bold') axes[1, 1].set_xlabel('每日讀書時數') axes[1, 1].set_ylabel('考試成績') axes[1, 1].grid(True, alpha=0.3) plt.tight_layout() plt.show()
🎨 效果: 2x2 四宮格圖表,一次展示多種數據!
# -*- coding: utf-8 -*- import pandas as pd import matplotlib.pyplot as plt # 設定中文字型 plt.rcParams["font.family"] = "Microsoft JhengHei" plt.rcParams["axes.unicode_minus"] = False # 建立資料 data = { '月份': ['1月', '2月', '3月', '4月', '5月', '6月'], '營業額': [150, 180, 165, 200, 220, 250], '成本': [90, 100, 95, 110, 120, 130], '利潤': [60, 80, 70, 90, 100, 120] } df = pd.DataFrame(data) # 設定月份為索引 df.set_index('月份', inplace=True) # 繪製多線圖 ax = df.plot(kind='line', figsize=(12, 6), marker='o', linewidth=2.5, markersize=8) # 設定標題和標籤 ax.set_title('2024 上半年營運數據分析', fontsize=18, fontweight='bold', pad=20) ax.set_xlabel('月份', fontsize=14) ax.set_ylabel('金額 (萬元)', fontsize=14) # 加入網格 ax.grid(True, alpha=0.3, linestyle='--') # 調整圖例位置 ax.legend(fontsize=12, loc='upper left') plt.tight_layout() plt.show() # 也可以繪製長條圖 df.plot(kind='bar', figsize=(12, 6), title='營運數據長條圖比較') plt.ylabel('金額 (萬元)') plt.xticks(rotation=0) plt.tight_layout() plt.show()
🎨 效果: 直接從 Pandas DataFrame 繪製圖表,超級方便!
pip install openai
前往 https://platform.openai.com
註冊帳號並取得 API Key
⚠️ 注意: API Key 是機密資訊,不要分享給他人或上傳到公開程式碼!
# -*- coding: utf-8 -*- from openai import OpenAI # 初始化 OpenAI 客戶端 client = OpenAI(api_key="你的-API-KEY") # 發送訊息給 AI def chat(message): response = client.chat.completions.create( model="gpt-5.6-luna", messages=[ {"role": "system", "content": "你是一個友善的中文助手"}, {"role": "user", "content": message} ] ) return response.choices[0].message.content # 測試對話 question = "請用繁體中文介紹 Python 的優點" answer = chat(question) print(f"問題: {question}") print(f"\nAI 回答:\n{answer}")
✅ 執行結果: AI 會用繁體中文回答您的問題!
💡 提示: 記得將 "你的-API-KEY" 替換成您實際的 API Key
# -*- coding: utf-8 -*- from openai import OpenAI # 初始化 client = OpenAI(api_key="你的-API-KEY") # 對話歷史記錄 conversation_history = [ {"role": "system", "content": "你是一個專業的 Python 程式教學助手,使用繁體中文回答"} ] def chat_with_memory(user_message): # 將使用者訊息加入歷史 conversation_history.append({ "role": "user", "content": user_message }) # 發送請求 response = client.chat.completions.create( model="gpt-5.6-luna", messages=conversation_history ) # 取得 AI 回應 ai_message = response.choices[0].message.content # 將 AI 回應加入歷史 conversation_history.append({ "role": "assistant", "content": ai_message }) return ai_message # 多輪對話範例 print("=== Python 學習助手 ===") print("(輸入 'quit' 結束對話)\n") while True: user_input = input("你: ") if user_input.lower() == 'quit': print("再見!") break response = chat_with_memory(user_input) print(f"\nAI: {response}\n")
🎉 功能: AI 會記住之前的對話,可以進行連續問答!
# -*- coding: utf-8 -*- from openai import OpenAI client = OpenAI(api_key="你的-API-KEY") def code_assistant(task, language="Python"): """程式碼生成助手""" prompt = f""" 請用 {language} 寫一個程式來完成以下任務: {task} 要求: 1. 程式碼要有詳細的中文註解 2. 包含錯誤處理 3. 提供使用範例 """ response = client.chat.completions.create( model="gpt-5.6-luna", messages=[ {"role": "system", "content": "你是專業的程式設計師"}, {"role": "user", "content": prompt} ] ) return response.choices[0].message.content # 使用範例 task1 = "讀取 CSV 檔案並計算平均值" code1 = code_assistant(task1) print("=== 任務: 讀取 CSV 並計算平均值 ===") print(code1) print("\n" + "="*50 + "\n") task2 = "建立一個簡單的計算機類別" code2 = code_assistant(task2) print("=== 任務: 建立計算機類別 ===") print(code2)
💡 應用場景
# -*- coding: utf-8 -*- from openai import OpenAI import pandas as pd client = OpenAI(api_key="你的-API-KEY") def data_analysis_assistant(data_description, question): """資料分析助手""" prompt = f""" 我有以下資料: {data_description} 問題: {question} 請提供: 1. 分析思路 2. 完整的 Python + Pandas 程式碼 3. 程式碼要有中文註解 """ response = client.chat.completions.create( model="gpt-5.6-luna", messages=[ {"role": "system", "content": "你是資料分析專家,精通 Pandas"}, {"role": "user", "content": prompt} ] ) return response.choices[0].message.content # 使用範例 data_desc = """ 一個學生成績資料表,包含以下欄位: - 姓名 (name) - 國文 (chinese) - 英文 (english) - 數學 (math) """ question = "如何找出總分最高的前 3 名學生?" answer = data_analysis_assistant(data_desc, question) print("=== 資料分析助手回答 ===") print(answer)
🎉 效果: AI 會提供完整的分析思路和可執行的程式碼!
解決方法:
pip install --upgrade jupyterlabjupyter lab --version (建議 3.6+)解決方法:
解決方法:
try-except 處理錯誤解決方法:
# 使用國內鏡像加速
pip install jupyterlab-language-pack-zh-TW -i https://pypi.tuna.tsinghua.edu.cn/simple
💡 快速設定檢查清單
pip install jupyterlabpip install jupyterlab-language-pack-zh-TWplt.rcParams["font.family"] = "字型名稱"pip install openai🎉 恭喜完成!
您已經掌握 Jupyter 中文化、資料視覺化和 AI 應用的完整技能!
現在可以開始您的資料分析和 AI 開發之旅了!