基于之前的问题: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()
关于python - Pandas/Pyplot 中的散点图 : How to plot by category with different markers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711078/