在线图中用标记突出显示单个点

Highlight a single point with a marker in lineplot

我想使用标记在我的线图上突出显示一个点。到目前为止,我设法创建了我的情节并在我想要的地方插入了亮点。

问题是我有 4 个不同的线图(4 个不同的分类属性)并且我将标记放置在每个单线图上,如下图所示:

我只想将标记放在 2020 年线(紫色线)上。到目前为止,这是我的代码:

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import seaborn as sns
import numpy as np
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(15,10))
gs0 = gridspec.GridSpec(2,2, figure=fig, hspace=0.2)

ax1 = fig.add_subplot(gs0[0,:]) # lineplot
ax2 = fig.add_subplot(gs0[1,0]) #Used for another plot not shown here
ax3 = fig.add_subplot(gs0[1,1]) #Used for another plot not shown here

flatui = ["#636EFA", "#EF553B", "#00CC96", "#AB63FA"]

sns.lineplot(ax=ax1,x="number of weeks", y="avg streams", hue="year", data=df, palette=flatui, marker = 'o', markersize=20, fillstyle='none', markeredgewidth=1.5, markeredgecolor='black', markevery=[5])

ax1.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.0f}'.format(x/1000) + 'K'))

ax1.set(title='Streams trend')
ax1.xaxis.set_major_locator(ticker.MultipleLocator(2))

我使用 markevery 字段在位置 5 放置了一个标记。有没有办法指定 line/category 在哪个位置放置我的标记?

编辑:这是我的数据框:

    avg streams date    year    number of weeks
0   145502.475  01-06   2017    0
1   158424.445  01-13   2017    1
2   166912.255  01-20   2017    2
3   169132.215  01-27   2017    3
4   181889.905  02-03   2017    4
... ... ... ... ...
181 760505.945  06-26   2020    25
182 713891.695  07-03   2020    26
183 700764.875  07-10   2020    27
184 753817.945  07-17   2020    28
185 717685.125  07-24   2020    29

186 rows × 4 columns

markevery 是一个 Line2D property. sns.lineplot doesn't return the lines so you need to get the line you want to annotate from the Axes。从 lineplot 调用中删除所有标记参数并添加 ...

lines = ax1.get_lines()

如果 2020 line/data 是系列中的第四个,

line = lines[3]
line.set_mark = 'o'
line.set_markersize = 20
line.set_markevery([5])
line.set_fillstyle('none')
line.set_markeredgewidth(1.5)
line.set_markeredgecolor('black')

# or
props = {'marker':'o','markersize':20, 'fillstyle':'none','markeredgewidth':1.5,
         'markeredgecolor':'black','markevery': [5]}
line.set(**props)

受 Quang Hoang 的评论启发,另一种选择是 添加 一个圆 around/at 从 DataFrame 派生点的点。

x = 5    # your spec
wk = df['number of weeks']==5
yr = df['year']==2020
s = df[wk & yr]
y = s['avg streams'].to_numpy()
# or 
y = df.loc[(df['year']==2020) & (df['number of weeks']==5),'avg streams'].to_numpy()

ax1.plot(x,y, 'ko', markersize=20, fillstyle='none', markeredgewidth=1.5)