Home > Backend Development > Python Tutorial > How to Create a Scatter Plot with Categorical Data in Python\'s Matplotlib?

How to Create a Scatter Plot with Categorical Data in Python\'s Matplotlib?

DDD
Release: 2024-12-20 10:46:11
Original
255 people have browsed it

How to Create a Scatter Plot with Categorical Data in Python's Matplotlib?

How to Create a Scatter Plot by Category

In Python's Matplotlib, creating a scatter plot by category can be achieved using the plot method, as demonstrated below:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

# Group Data
groups = df.groupby('label')

# Plot
fig, ax = plt.subplots()
ax.margins(0.05)  # Optional padding
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend()

plt.show()
Copy after login

For a more customized appearance resembling Pandas' default style:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

# Group Data
groups = df.groupby('label')

# Plot
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)
colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random')

fig, ax = plt.subplots()
ax.set_color_cycle(colors)
ax.margins(0.05)
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend(numpoints=1, loc='upper left')

plt.show()
Copy after login

The above is the detailed content of How to Create a Scatter Plot with Categorical Data in Python\'s Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template