gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:50:32 27 4
gpt4 key购买 nike

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

问题是我有 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

最佳答案

markevery 是一个 Line2D属性(property)。 sns.lineplot 不返回行,因此您需要从 the Axes 中获取要注释的行.从 lineplot 调用中删除所有标记参数并添加 ...

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 的评论启发,另一种选择是在从 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)

关于python - 在线图中用标记突出显示单个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63647545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com