Pandas/Pyplot中的散点图:如何使用不同的标记按类别进行绘图 [英] Scatter plots in Pandas/Pyplot: How to plot by category with different markers

查看:864
本文介绍了Pandas/Pyplot中的散点图:如何使用不同的标记按类别进行绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此先前的问题:熊猫/Pyplot:如何按类别绘制.

Building on this earlier question: Scatter plots in Pandas/Pyplot: How to plot by category.

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

The code below is the solution to that post and plots each group as a different color. How would one also plot each group as different marker?

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

推荐答案

在迭代组时,可以使用

While you iterate over your groups, you can iterate over a list of markers using zip. The code below will iterate over the markers list and assign each element, in turn, using marker=marker in the ax.plot line.

我还添加了 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()

这篇关于Pandas/Pyplot中的散点图:如何使用不同的标记按类别进行绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆