溫馨提示×

溫馨提示×

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

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

Python怎么實現折線圖、柱狀圖、餅圖

發布時間:2021-11-23 11:39:18 來源:億速云 閱讀:213 作者:iii 欄目:大數據
# Python怎么實現折線圖、柱狀圖、餅圖

數據可視化是數據分析中不可或缺的一環,Python憑借其豐富的庫生態系統成為實現可視化的首選工具。本文將詳細介紹如何使用Matplotlib和Seaborn庫繪制折線圖、柱狀圖和餅圖,并通過實際代碼示例展示完整實現過程。

## 一、環境準備與基礎庫介紹

### 1.1 安裝必要庫
在開始之前,請確保已安裝以下Python庫:
```python
pip install matplotlib seaborn numpy pandas

1.2 核心庫簡介

  • Matplotlib:Python最基礎的2D繪圖庫,提供類似MATLAB的繪圖接口
  • Seaborn:基于Matplotlib的高級可視化庫,默認樣式更美觀
  • Pandas:數據處理庫,完美配合可視化操作

二、折線圖實現

2.1 基礎折線圖

折線圖適合展示數據隨時間變化的趨勢。

import matplotlib.pyplot as plt
import numpy as np

# 生成示例數據
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 創建畫布和坐標系
plt.figure(figsize=(8, 4))

# 繪制折線圖
plt.plot(x, y, 
         color='royalblue',
         linestyle='-',
         linewidth=2,
         marker='o',
         markersize=4,
         label='sin(x)')

# 添加標題和標簽
plt.title('Basic Line Chart', fontsize=14)
plt.xlabel('X Axis', fontsize=12)
plt.ylabel('Y Axis', fontsize=12)

# 添加圖例和網格
plt.legend()
plt.grid(alpha=0.4)

# 顯示圖表
plt.show()

2.2 多線折線圖

比較多個數據序列的趨勢變化:

# 生成多組數據
x = np.arange(1, 11)
y1 = np.random.randint(10, 30, 10)
y2 = np.random.randint(20, 40, 10)
y3 = np.random.randint(5, 25, 10)

plt.figure(figsize=(9, 5))

# 繪制多條折線
plt.plot(x, y1, label='Product A', marker='s')
plt.plot(x, y2, label='Product B', marker='^')
plt.plot(x, y3, label='Product C', marker='D')

# 高級設置
plt.xticks(x, [f'Week {i}' for i in x])  # 自定義x軸刻度
plt.ylim(0, 50)  # 設置y軸范圍

# 添加數據標簽
for a, b in zip(x, y1):
    plt.text(a, b+1, str(b), ha='center')
    
plt.title('Sales Trend Comparison')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()

2.3 使用Seaborn優化樣式

import seaborn as sns
import pandas as pd

# 創建DataFrame數據
df = pd.DataFrame({
    'Month': ['Jan', 'Feb', 'Mar', 'Apr'],
    'Revenue': [45, 37, 52, 48],
    'Cost': [30, 25, 36, 32]
})

# 設置Seaborn樣式
sns.set_style("whitegrid")

# 繪制折線圖
sns.lineplot(data=df, x='Month', y='Revenue', 
             marker='o', label='Revenue')
sns.lineplot(data=df, x='Month', y='Cost', 
             marker='s', label='Cost')

plt.title('Business Performance')
plt.ylabel('Amount (million)')
plt.show()

三、柱狀圖實現

3.1 基礎柱狀圖

適合比較不同類別的數值大小。

categories = ['A', 'B', 'C', 'D']
values = [15, 24, 18, 27]

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

# 繪制柱狀圖
bars = plt.bar(categories, values, 
               color=['#3498db', '#2ecc71', '#f1c40f', '#e74c3c'],
               width=0.6)

# 添加數據標簽
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'{height}',
             ha='center', va='bottom')

plt.title('Basic Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()

3.2 堆疊/分組柱狀圖

# 準備數據
labels = ['Q1', 'Q2', 'Q3', 'Q4']
men = [20, 35, 30, 35]
women = [25, 32, 34, 20]

x = np.arange(len(labels))
width = 0.35

fig, ax = plt.subplots(figsize=(9, 5))

# 繪制分組柱狀圖
rects1 = ax.bar(x - width/2, men, width, label='Men')
rects2 = ax.bar(x + width/2, women, width, label='Women')

# 自定義設置
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and quarter')
ax.legend()

# 自動調整標簽位置
fig.tight_layout()
plt.show()

3.3 水平柱狀圖

countries = ['USA', 'China', 'Japan', 'Germany', 'UK']
gdp = [21.4, 14.3, 5.1, 3.9, 2.8]

plt.figure(figsize=(8, 4))
bars = plt.barh(countries, gdp, color='teal')

# 添加數據標簽
for bar in bars:
    width = bar.get_width()
    plt.text(width, bar.get_y() + bar.get_height()/2,
             f'${width}tr',
             va='center')

plt.title('GDP Comparison (2020)')
plt.xlabel('Trillion USD')
plt.grid(axis='x', alpha=0.3)
plt.show()

四、餅圖實現

4.1 基礎餅圖

適合展示比例分布關系。

sizes = [15, 30, 25, 10, 20]
labels = ['A', 'B', 'C', 'D', 'E']
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99', '#c2c2f0']

plt.figure(figsize=(6, 6))

# 繪制餅圖
patches, texts, autotexts = plt.pie(
    sizes, 
    labels=labels,
    colors=colors,
    autopct='%1.1f%%',
    startangle=90,
    explode=(0.05, 0, 0, 0, 0)  # 突出第一塊
)

# 設置文本樣式
for text in texts:
    text.set_size(12)
for autotext in autotexts:
    autotext.set_size(10)
    autotext.set_color('white')

plt.title('Basic Pie Chart', fontsize=14)
plt.show()

4.2 環形圖

# 數據準備
data = [35, 25, 20, 15, 5]
labels = ['Group A', 'Group B', 'Group C', 'Group D', 'Group E']

# 創建子圖
fig, ax = plt.subplots(figsize=(6, 6))

# 繪制環形圖
wedges, _ = ax.pie(data, radius=1, 
                   colors=sns.color_palette("Set2"),
                   wedgeprops=dict(width=0.3, edgecolor='w'))

# 添加圖例
ax.legend(wedges, labels,
          title="Categories",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.title('Donut Chart')
plt.show()

4.3 使用Pandas快速生成餅圖

# 創建Series數據
s = pd.Series([20, 30, 25, 25], 
              index=['A', 'B', 'C', 'D'])

# 直接調用plot方法
s.plot.pie(figsize=(6, 6),
           autopct='%.1f%%',
           explode=(0.1, 0, 0, 0),
           shadow=True,
           startangle=90)

plt.ylabel('')  # 移除默認的ylabel
plt.title('Pie Chart from Pandas')
plt.show()

五、實用技巧與常見問題

5.1 圖表保存

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

5.2 解決中文顯示問題

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

5.3 樣式主題設置

plt.style.use('ggplot')  # 可選: 'seaborn', 'fivethirtyeight'等

六、總結

本文詳細介紹了Python中使用Matplotlib和Seaborn繪制三種基礎圖表的方法:

  1. 折線圖:最適合展示數據隨時間變化的趨勢

    • 使用plt.plot()sns.lineplot()
    • 關鍵參數:marker, linestyle, linewidth
  2. 柱狀圖:最擅長比較不同類別的數值差異

    • 使用plt.bar()plt.barh()
    • 關鍵參數:width, color, edgecolor
  3. 餅圖:最有效展示整體中各部分的比例關系

    • 使用plt.pie()
    • 關鍵參數:autopct, explode, startangle

實際應用中應根據數據特點和展示目的選擇合適的圖表類型。對于更復雜的可視化需求,可以結合Pandas的數據處理能力和Seaborn的高級圖表功能來實現。 “`

向AI問一下細節

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

AI

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