Heim  >  Artikel  >  Backend-Entwicklung  >  Wie erstelle ich Streudiagramme mit unterschiedlichen Farben für kategoriale Ebenen in Python mithilfe von Matplotlib?

Wie erstelle ich Streudiagramme mit unterschiedlichen Farben für kategoriale Ebenen in Python mithilfe von Matplotlib?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 16:32:02786Durchsuche

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.

Das obige ist der detaillierte Inhalt vonWie erstelle ich Streudiagramme mit unterschiedlichen Farben für kategoriale Ebenen in Python mithilfe von Matplotlib?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
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