在折线图中使用标记高亮单个数据点

3
我想在线性图上使用标记突出显示一个单独的点。到目前为止,我已经创建了我的图并在所需位置插入了突出显示。
问题是我有4个不同的线性图(4个不同的分类属性),并且我在每个单独的线性图上都放置了标记,如下图所示:

Plot

我希望将标记仅放置在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处放置标记。是否有办法指定在哪一行/类别上放置我的标记? 编辑: 这是我的数据框:
    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

2
只需要执行 ax1.scatter([5]*df.shape[1], df.loc[5]) 吗? - Quang Hoang
1
虽然无关紧要,但实际上不需要保存 plot == ax1,你可以使用 plot = sns.lineplot(...) - Guimoute
@Guimoute 已修复,这是由于复制粘贴导致的“虚假”代码。 - Mattia Surricchio
1
请勿发布代码、数据或Tracebacks的图像。请将其复制并粘贴为文本,然后将其格式化为代码(选择它并键入ctrl-k)... 不鼓励截屏代码和/或错误 - wwii
1
@wwii 编辑并将数据框插入为代码片段 - Mattia Surricchio
1个回答

4
markevery 是一个 Line2D 属性。 sns.lineplot 不返回线条,因此您需要从 中获取要进行 注释 的线条。从 lineplot 调用中删除所有的 marker 参数,然后添加...
lines = ax1.get_lines()

如果2020年的数据是该系列的第四个。
line = lines[3]
line.set_marker('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 评论的启发,是在导出数据点处添加一个圆圈。
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)

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