如何使用 Matplotlib 在 Python 中為分類等級建立具有不同顏色的散佈圖?

Mary-Kate Olsen
發布: 2024-10-17 16:32:02
原創
784 人瀏覽過

How to Create Scatter Plots with Distinct Colors for Categorical Levels in Python Using Matplotlib?

Drawing Scatter Plots with Different Colors for Categorical Levels in Python with Matplotlib

In Matplotlib, a Python library for creating static, animated, and interactive visualizations in Python, you can plot different scatter plots with different colors for each level of a categorical variable by leveraging the c argument of the plt.scatter function.

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

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6], 'color': ['red', 'blue', 'green']})

colors = {'red': 'tab:red', 'blue': 'tab:blue', 'green': 'tab:green'}

plt.scatter(df['x'], df['y'], c=df['color'].map(colors))
plt.show()</code>
登入後複製

By passing the c argument, a dictionary mapping color names to RGB values can be used to specify the color of each point. The map method of Pandas then applies the color mapping to the df['color'] column, effectively assigning each point a unique color.

<code class="python">colors = {'D': 'tab:blue', 'E': 'tab:orange', 'F': 'tab:green', 'G': 'tab:red', 'H': 'tab:purple', 'I': 'tab:brown', 'J': 'tab:pink'}

ax.scatter(df['carat'], df['price'], c=df['color'].map(colors))</code>
登入後複製

This approach allows for a more customized color scheme and greater control over the colors used in the plot. By using a color dictionary, users can easily modify the color scheme as needed.

以上是如何使用 Matplotlib 在 Python 中為分類等級建立具有不同顏色的散佈圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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