如何在matplotlib图中突出显示一个点

24
假设我有以下两个列表,分别对应x和y坐标。
x = [1,2,3,4,5,6]
y = [3,4,5,6,7,8]

我想让第一对(1,3)以不同的颜色或形状呈现。

如何使用Python实现这个功能?


你想要改变散点图中第一对数据的颜色和形状吗? - KenHBS
是的,没错。那就是我需要做的。 - Abhinav Goel
2个回答

30

其中一个最简单的可能答案。

import matplotlib.pyplot as plt

x = [1,2,3,4,5,6]
y = [3,4,5,6,7,8]

plt.plot(x[1:], y[1:], 'ro')
plt.plot(x[0], y[0], 'g*')

plt.show()

2
这是指绿色的星号——就像这样*,但是是绿色的。 - Bill Bell

1

使用scatter()函数可以提供更多的灵活性,您可以更直观地更改标记的样式、大小和颜色(例如使用D表示钻石形状)。

x = [1,2,3,4,5,6]
y = [3,4,5,6,7,8]

plt.scatter(x[1:], y[1:], c='blue')
plt.scatter(x[0], y[0], c='red', marker='D', s=100);

img

# you can even write text as a marker
plt.scatter(x[0], y[0], c='red', marker=r'$\tau$', s=100);

如果要突出显示的点不是第一个点,则过滤掩码可能会有用。例如,以下代码突出显示第三个点。
plt.scatter(*zip(*(xy for i, xy in enumerate(zip(x, y)) if i!=2)), marker=6)
plt.scatter(x[2], y[2], c='red', marker=7, s=200);

也许,使用numpy进行过滤更简单。

data = np.array([x, y])                                # construct a single 2d array
plt.scatter(*data[:, np.arange(len(x))!=2], marker=6)  # plot all except the third point
plt.scatter(*data[:, 2], c='red', marker=7, s=200);    # plot the third point

img2

另外一方面,您可以在 这里 找到完整的标记样式字典,或者通过 matplotlib.markers.MarkerStyle.markers

# a dictionary of marker styles
from matplotlib.markers import MarkerStyle
MarkerStyle.markers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接