srm*_*ahy 3 python matplotlib pandas
基于之前的问题:ScatterplotsinPandas/Pyplot:Howtoplotbycategory。
下面的代码是该帖子的解决方案,并将每个组绘制为不同的颜色。如何将每一组绘制为不同的标记?
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()
Run Code Online (Sandbox Code Playgroud)
当您迭代组时,您可以使用 迭代标记列表zip。下面的代码将迭代列表markers并依次分配每个元素,并marker=marker在行中使用ax.plot。
我还添加了itertools.cycle这将导致迭代在到达终点后从头开始,这意味着如果您有超过 3 个组,那么它不会失败。'x', 'o', '^', 'x'例如,如果您有 4 个组,则标记将为。
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()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
8488 次 |
| 最近记录: |