如何使用 pandas 和 Matplotlib 在 Python 中按列值對散佈圖著色?

Susan Sarandon
發布: 2024-10-19 14:52:01
原創
750 人瀏覽過

How to Color Scatter Plots by Column Values in Python with pandas and Matplotlib?

使用pandas 和Matplotlib 在Python 中按列值繪製顏色散點圖

簡介

正如您所提到的,ggplot2 提供了方便美觀定制,允許您根據列值對散點圖進行著色。本文使用 pandas 和 Matplotlib 來探索 Python 中的等效功能。

使用 Seaborn 的解決方案

Seaborn 是一個 Python 資料視覺化函式庫,為這個問題提供了一個優雅的解決方案。

<code class="python">import seaborn as sns

# Load and clean the data
data = pd.read_csv('data.csv')
data['Gender'] = data['Gender'].astype('category')

# Create the scatter plot with color mapping
sns.relplot(data=data, x='Weight', y='Height', hue='Gender')</code>
登入後複製

此程式碼利用 relplot 函數建立散佈圖,色調參數根據性別列分配顏色。

使用 Matplotlib 和 Dictionary 的解決方案

如果您喜歡直接使用 Matplotlib,您可以建立一個顏色映射字典並用它來為點著色。

<code class="python">import matplotlib.pyplot as plt
import numpy as np

# Load and clean the data
data = pd.read_csv('data.csv')
data['Gender'] = data['Gender'].astype('category')

# Create a color mapping dictionary
categories = np.unique(data['Gender'])
colors = np.linspace(0, 1, len(categories))
color_dict = dict(zip(categories, colors))

# Add a 'Color' column to the DataFrame
data['Color'] = data['Gender'].map(color_dict)

# Create the scatter plot
plt.scatter(data['Weight'], data['Height'], c=data['Color'])
plt.show()</code>
登入後複製

在這個方法中,color_dict 為每個類別指派顏色性別欄位。 DataFrame 中新增了「Color」列,scatter 函數中的 c 參數使用此列來確定每個點的顏色。

其他自訂

Seaborn 和 Matplotlib 都允許進一步自訂散點圖,例如調整調色板或添加圖例。請參閱他們的文件以了解更多選項。

結論

您可以直接使用 Seaborn 或 Matplotlib 在 Python 中輕鬆地按列值對散點圖進行顏色著色。 Seaborn 提供了方便的進階介面,而 Matplotlib 提供了更大的客製化控制。透過利用上述技術,您可以在 Python 中建立資訊豐富且具有視覺吸引力的散點圖。

以上是如何使用 pandas 和 Matplotlib 在 Python 中按列值對散佈圖著色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!