使用Python的Pandas和Matplotlib來讀取.csv檔案並進行資料可視化是一個常見的數據分析流程。以下是詳細的教學文章,將使用不同的公開資料集來展示如何繪製折線圖、柱狀圖、散點圖和圓餅圖。
首先,確保您已安裝必要的Python庫。如果尚未安裝,可以使用以下命令:
pip install pandas matplotlib
在開始之前,您需要引入Pandas和Matplotlib模組:
import pandas as pd
import matplotlib.pyplot as plt
以下是四個不同的公開資料集及其對應的CSV檔案URL:
我們將繪製美國國家氣象局的氣溫資料集中的乘客數量隨時間變化的折線圖:
import pandas as pd
import matplotlib.pyplot as plt
# 讀取氣溫資料集
url_temp = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
df_temp = pd.read_csv(url_temp)
# 繪製折線圖
plt.figure(figsize=(10, 6)) # 創建一個新的圖形,指定大小(寬度,高度)
plt.plot(df_temp['Month'], df_temp['Passengers'], marker='o') # 繪製 'Month' 為 x 軸,'Passengers' 為 y 軸,並使用圓形標記
plt.title('Monthly Airline Passengers') # 設定圖表的標題
plt.xlabel('Month') # 設定 x 軸的標籤
plt.ylabel('Number of Passengers') # 設定 y 軸的標籤
plt.xticks(rotation=450) # 將 x 軸標籤旋轉 45 度,以便更清晰地顯示
plt.grid()
plt.show()
4. 柱狀圖
接下來,我們將繪製世界銀行的GDP資料集中各國GDP的柱狀圖:
import pandas as pd
import matplotlib.pyplot as plt
# 讀取GDP資料集
url_gdp = "https://raw.githubusercontent.com/datasets/gdp/master/data/gdp.csv"
df_gdp = pd.read_csv(url_gdp)
# 篩選前10個國家的GDP數據
top_gdp = df_gdp.groupby('Country Name')['Value'].last().nlargest(10)
# 繪製柱狀圖
plt.figure(figsize=(10, 6))
top_gdp.plot(kind='bar', color='skyblue')
plt.title('Top 10 Countries by GDP')
plt.xlabel('Country')
plt.ylabel('GDP (in USD)')
plt.xticks(rotation=45)
plt.show()
5. 散點圖
接下來,我們將使用Iris資料集繪製花瓣長度與花瓣寬度之間的散點圖:
import pandas as pd
import matplotlib.pyplot as plt
# 讀取Iris資料集
url_iris = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
df_iris = pd.read_csv(url_iris, header=None, names=["sepal_length", "sepal_width", "petal_length", "petal_width", "species"])
# 繪製散點圖
plt.figure(figsize=(10, 6))
scatter = plt.scatter(df_iris['petal_length'], df_iris['petal_width'], c=df_iris['species'].astype('category').cat.codes, cmap='viridis') # c參數:將不同的花種 (species) 轉換為數字類別,並以顏色區分。cmap參數:指定顏色映射為 'viridis'。
plt.title('Scatter Plot of Petal Length vs Width')
plt.xlabel('Petal Length (cm)')
plt.ylabel('Petal Width (cm)')
legend1 = plt.legend(*scatter.legend_elements(), title="Species") # 為不同的花種創建圖例,圖例標題為 "Species"。 # scatter.legend_elements() 方法會自動生成對應於數據點顏色的圖例元素。
plt.gca().add_artist(legend1) # 將圖例添加到當前的軸對象中。
plt.grid()
plt.show()
6. 圓餅圖
最後,我們將繪製各國人口資料集中各大洲人口比例的圓餅圖:
import pandas as pd
import matplotlib.pyplot as plt
# 讀取人口資料集
url_population = "https://raw.githubusercontent.com/datasets/population/master/data/population.csv"
df_population = pd.read_csv(url_population)
# 計算各大洲人口總和
continent_population = df_population.groupby('Country Name')['Value'].sum()
# 繪製圓餅圖
plt.figure(figsize=(8, 8))
plt.pie(continent_population, labels=continent_population.index, autopct='%1.1f%%', startangle=140)
plt.title('Population Distribution by Country')
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
以上步驟展示了如何使用Pandas讀取不同公開資料集的.csv檔案並利用Matplotlib進行各種資料可視化。透過這些圖表,您可以更有效地分析和理解數據。根據需求,大家可以進一步調整參數和圖表類型,以探索和展示各種數據。