如何在散点图pylab中为不同的点使用不同的标记
How to use different marker for different point in scatter plot pylab
我想用pylab的散点图功能
x = [1,2,3,4,5]
y = [2,1,3,6,7]
这5个点有两个簇,索引1-2(簇1)和索引2-4(簇2)。簇 1 中的点应使用标记“^”,而簇 2 中的点应使用标记 's'。所以
cluster = ['^','^','^','s','s']
我试过了
fig, ax = pl.subplots()
ax.scatter(x,y,marker=cluster)
pl.show()
这是一个玩具示例,真实数据有超过 10000 个样本
要实现此结果,您需要在同一轴上多次调用 scatter
。好消息是您可以针对给定的数据自动执行此操作:
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]
cluster = ['^','^','^','s','s']
fig, ax = plt.subplots()
for xp, yp, m in zip(x, y, cluster):
ax.scatter([xp],[yp], marker=m)
plt.show()
一个更简洁的解决方案是使用集群信息过滤输入数据。我们可以使用 numpy
.
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1,2,3,4,5])
y = np.array([2,1,3,6,7])
cluster = np.array([1,1,1,2,2])
fig, ax = plt.subplots()
ax.scatter(x[cluster==1],y[cluster==1], marker='^')
ax.scatter(x[cluster==2],y[cluster==2], marker='s')
plt.show()
我想用pylab的散点图功能
x = [1,2,3,4,5]
y = [2,1,3,6,7]
这5个点有两个簇,索引1-2(簇1)和索引2-4(簇2)。簇 1 中的点应使用标记“^”,而簇 2 中的点应使用标记 's'。所以
cluster = ['^','^','^','s','s']
我试过了
fig, ax = pl.subplots()
ax.scatter(x,y,marker=cluster)
pl.show()
这是一个玩具示例,真实数据有超过 10000 个样本
要实现此结果,您需要在同一轴上多次调用 scatter
。好消息是您可以针对给定的数据自动执行此操作:
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]
cluster = ['^','^','^','s','s']
fig, ax = plt.subplots()
for xp, yp, m in zip(x, y, cluster):
ax.scatter([xp],[yp], marker=m)
plt.show()
一个更简洁的解决方案是使用集群信息过滤输入数据。我们可以使用 numpy
.
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1,2,3,4,5])
y = np.array([2,1,3,6,7])
cluster = np.array([1,1,1,2,2])
fig, ax = plt.subplots()
ax.scatter(x[cluster==1],y[cluster==1], marker='^')
ax.scatter(x[cluster==2],y[cluster==2], marker='s')
plt.show()