python - Pandas/Pyplot 中的散点图 : How to plot by category with different markers

标签 python matplotlib pandas

基于之前的问题:Scatter plots in Pandas/Pyplot: How to plot by category

下面的代码是该帖子的解决方案,并将每个组绘制为不同的颜色。如何将每一组绘制为不同的标记?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# 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))

groups = df.groupby('label')

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

plt.show()

最佳答案

在迭代组时,您可以使用 zip 迭代标记列表。 。下面的代码将迭代 markers 列表,并使用 ax.plot 行中的 marker=marker 依次分配每个元素。

我还添加了 itertools.cycle一旦到达终点,这将导致迭代从头开始,这意味着如果你有超过 3 个组,那么它不会失败。例如,如果您有 4 个组,则标记将为'x'、'o'、'^'、'x'

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

from itertools import cycle

# 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))

groups = df.groupby('label')

markers = ['x', 'o', '^']

# Plot
fig, ax = plt.subplots()
ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
for (name, group), marker in zip(groups, cycle(markers)):
    ax.plot(group.x, group.y, marker=marker, linestyle='', ms=12, label=name)
ax.legend()

plt.show()

Example plot

关于python - Pandas/Pyplot 中的散点图 : How to plot by category with different markers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711078/

相关文章:

python - 通过 cron 运行时获取 subprocess.Popen stdout

python - 如何从flask中的中间件(app.before_request())返回flask响应?

python - Matplotlib 自动缩放共享 x 轴图形的子图的垂直高度

python - 创建具有重复值的数据框

python - 将 Pandas 'categorical' dtype 与 sklearn 一起使用

python - 在 Windows 10 上从 Python 获取准确的文件创建日期

python - 使用 py2app 捆绑 PyQt5 应用程序 : keep getting "Abort trap: 6" error

python - 使用 Matplotlib 创建多个绘图

python - 不同颜色的 Pandas 绘图栏无法按预期工作

python - 如何在大数据框中对组内的行进行排序