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.
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.
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>
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.
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.
The above is the detailed content of How Do I Use Matplotlib to Plot Distinct Colors for Various Categorical Levels?. For more information, please follow other related articles on the PHP Chinese website!