Wie kodiere ich Streudiagrammkategorien in Matplotlib farblich?

Susan Sarandon
Freigeben: 2024-10-17 16:39:02
Original
162 Leute haben es durchsucht

How to Color-Code Scatter Plot Categories in Matplotlib?

How to Plot Different Colors for Different Categorical Levels in Matplotlib

Problem

Given a DataFrame with categorical variables, you want to create a scatter plot where each category has its own color.

Solution with Matplotlib

To specify colors for different categories in Matplotlib, use the c argument in plt.scatter. This argument accepts an array of colors or a mapping that maps categories to colors.

Here's an example:

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

# Define a DataFrame
df = pd.DataFrame({'category': ['A', 'B', 'C'], 'value': [10, 20, 30]})

# Create the scatter plot
colors = {'A': 'red', 'B': 'green', 'C': 'blue'}
plt.scatter(df['category'], df['value'], c=df['category'].map(colors))
plt.show()</code>
Nach dem Login kopieren

This code assigns red, green, and blue colors to categories 'A', 'B', and 'C', respectively.

DataFrame GroupBy and Plotting

Alternatively, you can use DataFrame.groupby() and .plot() to achieve the same result:

<code class="python">fig, ax = plt.subplots(figsize=(6, 6))

df.groupby('category').plot(ax=ax, kind='scatter', x='category', y='value', color=colors)
plt.show()</code>
Nach dem Login kopieren

This code assumes the existence of a colors dictionary that maps categories to colors.

Das obige ist der detaillierte Inhalt vonWie kodiere ich Streudiagrammkategorien in Matplotlib farblich?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!