Bagaimana untuk Kategori Plot Taburan Kod Warna dalam Matplotlib?

Susan Sarandon
Lepaskan: 2024-10-17 16:39:02
asal
166 orang telah melayarinya

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>
Salin selepas log masuk

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>
Salin selepas log masuk

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

Atas ialah kandungan terperinci Bagaimana untuk Kategori Plot Taburan Kod Warna dalam Matplotlib?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!