溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python怎么把數據寫入列表并導出折線圖

發布時間:2022-01-11 13:39:44 來源:億速云 閱讀:296 作者:iii 欄目:開發技術
# Python怎么把數據寫入列表并導出折線圖

在數據分析和可視化領域,Python憑借其強大的庫支持成為最受歡迎的工具之一。本文將詳細介紹如何將數據寫入列表,并使用Matplotlib庫生成折線圖導出為圖片文件。

---

## 一、數據寫入Python列表

### 1.1 創建空列表
列表(List)是Python中最基礎的數據結構之一,用方括號`[]`表示:

```python
data_list = []  # 創建空列表

1.2 添加數據的5種方法

方法1:append()逐個添加

data_list.append(10)
data_list.append(20)
# 結果:[10, 20]

方法2:extend()批量添加

data_list.extend([30, 40, 50])
# 結果:[10, 20, 30, 40, 50]

方法3:列表推導式

squares = [x**2 for x in range(1,6)]
# 結果:[1, 4, 9, 16, 25]

方法4:+運算符合并

new_list = data_list + [60, 70]

方法5:從文件讀取

with open('data.txt') as f:
    file_data = [float(line.strip()) for line in f]

1.3 多維列表示例

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

二、使用Matplotlib繪制折線圖

2.1 安裝Matplotlib

pip install matplotlib

2.2 基礎折線圖繪制

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.show()

2.3 圖表定制化

添加標題和標簽

plt.title("示例折線圖")
plt.xlabel("X軸標簽")
plt.ylabel("Y軸標簽")

設置樣式

plt.plot(x, y, 
         color='red', 
         linestyle='--',
         marker='o',
         linewidth=2)

添加圖例

plt.plot(x, y, label='趨勢線')
plt.legend()

設置坐標范圍

plt.xlim(0, 6)
plt.ylim(0, 12)

三、導出圖表到文件

3.1 保存為圖片

plt.savefig('output.png', dpi=300, bbox_inches='tight')

支持格式: - PNG(默認) - JPG(output.jpg) - SVG(矢量圖) - PDF(可縮放文檔)

3.2 高級導出設置

plt.savefig('high_quality.png',
           dpi=600,          # 提高分辨率
           quality=95,       # JPG質量
           transparent=True) # 透明背景

四、完整案例演示

4.1 溫度數據可視化

import matplotlib.pyplot as plt
from datetime import datetime

# 數據準備
dates = ['2023-01-01', '2023-01-02', '2023-01-03']
temps = [22.5, 24.3, 19.8]

# 轉換日期格式
x = [datetime.strptime(d, '%Y-%m-%d') for d in dates]

# 創建畫布
plt.figure(figsize=(10, 6))

# 繪制折線圖
plt.plot(x, temps, 
        marker='s', 
        color='#FF6B6B',
        label='日平均溫度')

# 添加標注
for i, txt in enumerate(temps):
    plt.annotate(f"{txt}°C", (x[i], temps[i]), 
                textcoords="offset points",
                xytext=(0,10), 
                ha='center')

# 圖表裝飾
plt.title("2023年1月溫度變化趨勢", pad=20)
plt.xlabel("日期")
plt.ylabel("溫度(°C)")
plt.grid(alpha=0.3)
plt.legend()

# 導出文件
plt.savefig('temperature_trend.png')
plt.close()  # 釋放內存

4.2 運行效果說明

  1. 生成10x6英寸的圖表
  2. 顯示帶有方塊標記的紅色折線
  3. 每個數據點上方顯示溫度值
  4. 添加淺色網格線
  5. 最終導出為PNG文件

五、常見問題解決

5.1 中文顯示問題

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

5.2 圖表元素重疊

調整畫布大?。?/p>

plt.figure(figsize=(12, 7))

5.3 導出圖片模糊

提高DPI參數:

plt.savefig('output.png', dpi=600)

六、擴展應用

6.1 結合Pandas使用

import pandas as pd

df = pd.DataFrame({
    'Month': ['Jan', 'Feb', 'Mar'],
    'Sales': [1200, 1800, 1500]
})

df.plot(x='Month', y='Sales', kind='line')
plt.savefig('sales.png')

6.2 動態更新圖表

from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
x, y = [], []

def update(frame):
    x.append(frame)
    y.append(frame**2)
    ax.clear()
    ax.plot(x, y)
    
ani = FuncAnimation(fig, update, frames=range(10))
ani.save('dynamic.gif', writer='pillow')

通過本文的學習,您應該已經掌握: 1. Python列表的基本操作方法 2. Matplotlib繪制折線圖的完整流程 3. 圖表導出為圖片文件的技術細節 4. 實際應用中的問題解決方案

建議讀者嘗試修改示例代碼中的參數,觀察不同設置對圖表效果的影響,這是掌握數據可視化的最佳實踐方式。 “`

這篇文章共計約1350字,采用Markdown格式編寫,包含: - 6個主要章節 - 15個代碼示例 - 多級標題結構 - 重點內容強調 - 實際應用案例 - 常見問題解決方案

可根據需要調整代碼示例的具體參數或補充其他可視化庫(如Seaborn)的相關內容。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女