首頁  >  文章  >  後端開發  >  如何使用 Matplotlib 繪製不同類別等級的不同顏色?

如何使用 Matplotlib 繪製不同類別等級的不同顏色?

DDD
DDD原創
2024-10-17 16:40:03424瀏覽

How Do I Use Matplotlib to Plot Distinct Colors for Various Categorical Levels?

How to Plot Different Colors for Different Categorical Levels in Python Using Only Matplotlib

Introduction

This article addresses how to create a scatter plot in Python using matplotlib, where each color represents a different categorical level. This approach avoids using auxiliary plotting packages like seaborn and ggplot for Python.

With Matplotlib

Matplotlib provides the c argument in plt.scatter, which allows color customization. Here's an example:

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

# Sample DataFrame
df = pd.DataFrame({'carat': [0.23, 0.21, 0.23],
                    'price': [326, 326, 327],
                    'color': ['E', 'E', 'E']})

# Color mapping
colors = {'D': 'tab:blue', 'E': 'tab:orange', 'F': 'tab:green', 'G': 'tab:red', 'H': 'tab:purple', 'I': 'tab:brown', 'J': 'tab:pink'}

# Scatter plot with colors
plt.scatter(df['carat'], df['price'], c=df['color'].map(colors))
plt.show()</code>

The map(colors) function maps the "diamond" colors to the "plotting" colors.

With seaborn

Although this article focuses on matplotlib, it's worth mentioning that seaborn also offers a convenient solution:

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

# Scatter plot with colors
sns.lmplot(x='carat', y='price', data=df, hue='color', fit_reg=False)</code>

With pandas.DataFrame.groupby & pandas.DataFrame.plot

For a manual approach, you can use pandas to group by color and plot each group separately:

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

# Sample DataFrame
df = pd.DataFrame({'carat': [0.23, 0.21, 0.23],
                    'price': [326, 326, 327],
                    'color': ['E', 'E', 'E']})

# Color mapping
colors = {'D': 'tab:blue', 'E': 'tab:orange', 'F': 'tab:green', 'G': 'tab:red', 'H': 'tab:purple', 'I': 'tab:brown', 'J': 'tab:pink'}

# Group by color and plot
grouped = df.groupby('color')
for key, group in grouped:
    group.plot(ax=plt.gca(), kind='scatter', x='carat', y='price', label=key, color=colors[key])

plt.show()</code>

This assumes the same DataFrame as before and manually assigns colors during the plotting process.

Conclusion

This article has demonstrated how to plot different colors for different categorical levels in Python using matplotlib, along with additional options using seaborn and a manual approach with pandas.

以上是如何使用 Matplotlib 繪製不同類別等級的不同顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn