如何在给定的地块上绘制垂直线(graph of a vertical line)

给定时间表示中的信号图,如何绘制标记相应时间索引的线?

给定时间表示中的信号图,如何绘制标记相应时间索引的线?

具体来说,给定一个时间索引范围从 0 到 2.6(秒)的信号图,我想为列表[0.22058956, 0.33088437, 2.20589566]绘制垂直的红线,表示相应的时间索引。

671

添加覆盖整个绘图窗口的垂直线而无需指定其实际高度的标准方法是plt.axvline

import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)

xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
    plt.axvline(x=xc)

您可以使用许多可用于其他绘图命令的关键字(例如colorlinestylelinewidth...)。您可以传入关键字参数yminymax如果您喜欢在轴上的 corrdinate(例如ymin=0.25ymax=0.75将覆盖

108
matplotlib.pyplot.vlinesvs.matplotlib.pyplot.axvline

这些方法适用于使用 seaborn 和pandas.DataFrame.plot生成的图,它们都使用matplotlib

区别在于vlines接受x的一个或多个位置,而axvline允许一个位置。

单个位置:x=37

多个位置:x=[37, 38, 39]

vlinesyminymax作为 y 轴上的位置,而axvlineyminymax作为 y 轴范围的百分比。

将多行传递给vlines时,将list传递给yminymax

对于面向对象的 API,还有matplotlib.axes.Axes.vlinesmatplotlib.axes.Axes.axvline

如果您使用fig, ax = plt.subplots()绘制图形,则将plt.vlinesplt.axvline分别替换为ax.vlinesax.axvline

有关.hlines的水平线,请参见此answer

import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(10, 7))
# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')
# only one line may be specified; ymin & ymax specified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
# place the legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
plt.show()

Enter image description here

Seaborn 轴级图

import seaborn as sns
# sample data
fmri = sns.load_dataset("fmri")
# x index for max y values for stim and cue
c_max, s_max = fmri.pivot_table(index='timepoint', columns='event', values='signal', aggfunc='mean').idxmax()
# plot
g = sns.lineplot(data=fmri, x="timepoint", y="signal", hue="event")
# y min and max
ymin, ymax = g.get_ylim()
# vertical lines
g.vlines(x=[c_max, s_max], ymin=ymin, ymax=ymax, colors=['tab:orange', 'tab:blue'], ls='--', lw=2)

Enter image description here

Seaborn 图级图

每个轴都必须迭代。

import seaborn as sns
# sample data
fmri = sns.load_dataset("fmri")
# used to get the index values (x) for max y for each event in each region
fpt = fmri.pivot_table(index=['region', 'timepoint'], columns='event', values='signal', aggfunc='mean')
# plot
g = sns.relplot(data=fmri, x="timepoint", y="signal", col="region", hue="event", kind="line")
# iterate through the axes
for ax in g.axes.flat:
    # get y min and max
    ymin, ymax = ax.get_ylim()
    # extract the region from the title for use in selecting the index of fpt
    region = ax.get_title().split(' = ')[1]
    # get x values for max event
    c_max, s_max = fpt.loc[region].idxmax()
    # add vertical lines
    ax.vlines(x=[c_max, s_max], ymin=ymin, ymax=ymax, colors=['tab:orange', 'tab:blue'], ls='--', lw=2, alpha=0.5)

对于'region = frontal',两个事件的最大值都出现在5

enter image description here

柱状图和直方图

请注意,条形图刻度位置具有zero-based索引,而与轴刻度标签无关,因此请根据条形图索引而不是刻度标签选择x

ax.get_xticklabels()将显示位置和标签。

import pandas as pd
import seaborn as sns
# load data
tips = sns.load_dataset('tips')
# histogram
ax = tips.plot(kind='hist', y='total_bill', bins=30, ec='k', title='Histogram with Vertical Line')
_ = ax.vlines(x=16.5, ymin=0, ymax=30, colors='r')
# barplot
ax = tips.loc[5:25, ['total_bill', 'tip']].plot(kind='bar', figsize=(15, 4), title='Barplot with Vertical Lines', rot=0)
_ = ax.vlines(x=[0, 17], ymin=0, ymax=45, colors='r')

Enter image description here

Enter image description here

时间序列轴

要作为 x 轴的数据框中的日期必须是datetime dtype。如果列或索引的类型不正确,则必须使用pd.to_datetime进行转换。

如果使用日期数组或列表,请分别参考Converting numpy array of strings to datetimeConvert datetime list into date python

x将接受像'2020-09-24'datetime(2020, 9, 2)这样的日期。

import pandas_datareader as web  # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
# get test data; this data is downloaded with the Date column in the index as a datetime dtype
df = web.DataReader('^gspc', data_source='yahoo', start='2020-09-01', end='2020-09-28').iloc[:, :2]
# display(df.head(2))
                   High          Low
Date                                
2020-09-01  3528.030029  3494.600098
2020-09-02  3588.110107  3535.229980
# plot dataframe; the index is a datetime index
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')
# add vertical lines
ax.vlines(x=[datetime(2020, 9, 2), '2020-09-24'], ymin=3200, ymax=3600, color='r', label='test lines')
ax.legend(bbox_to_anchor=(1, 1), loc='upper left')
plt.show()

Enter image description here

90

对于多行

xposition = [0.3, 0.4, 0.45]
for xc in xposition:
    plt.axvline(x=xc, color='k', linestyle='--')
53

要添加一个legend和 / 或colors到一些垂直线,然后使用这个:

import matplotlib.pyplot as plt
# x coordinates for the lines
xcoords = [0.1, 0.3, 0.5]
# colors for the lines
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
    plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()

后果

My amazing plot seralouk

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(926)
搜索查询中的两个聚合的总和(sumo logic aggregate)
上一篇
MATLAB导入文件的最大大小应该是多少
下一篇

相关推荐

  • cvt和自动挡哪个好提升驾驶体验的最佳选择

    CVT(可变转换器)是一种由传动带及传动轮组成的无级变速器,它可以在没有传动档位的情况下,根据驾驶者的驾驶习惯,自动调整传动轮之间的转速比,从而实现无级变速。自动挡是指车辆自动变速箱,它使用液力传动来实现变速,可以自动适应车辆的行驶状态,减少司机的疲劳,提高行车的舒适性。…

    2023-06-08 07:42:19
    0 16 20
  • cv一叶扁舟和清影轩阳:漫游在一叶扁舟和清影轩阳之间

    cv一叶扁舟是一款开源的计算机视觉库,用于图像处理、计算机视觉等。它提供了丰富的API,可以帮助开发者快速实现各种图像处理任务,如图像分割、目标检测、图像识别等。清影轩阳是一款开源的计算机视觉框架,用于图像处理、目标检测、分类等。它提供了丰富的API,可以帮助开发者快速实现各种图像处理任务,如图像分割、目标检测、图像识别等。…

    2023-08-05 07:06:20
    0 32 85
  • css设置滚动条宽度设置:This is a title

    CSS设置滚动条宽度的方法:使用CSS3的。-webkit-属性:…

    2023-06-06 10:53:01
    0 26 46
  • xl和xe汽车cvt:探索XL和XE汽车的CVT技术优势

    XL和XE汽车CVT是一种变速器,它使用液力变矩器代替传统的机械变速器,以达到更高的效率。它的工作原理是,当发动机输出功率时,液力变矩器就会将这些功率转换为液压能量,然后将能量传递到变速器的输出轴上,从而实现变速。…

    2023-04-09 00:41:04
    0 71 30
  • cordon bleu是什么意思:法式炸鸡卷——Cordon Bleu的经典之作

    Cordon Bleu是一种烹饪技术,其中肉片被置于奶酪和火腿之间,然后用面包屑裹上,最后煎炸或烤熟。这种技术通常用于制作鸡肉,但也可以用于制作其他类型的肉类,如牛肉或猪肉。…

    2024-01-27 15:13:30
    0 56 68
  • countif 非空:非空单元格的计数

    Countif 非空是指计算某个单元格不为空的数量。代码如下:…

    2023-04-22 15:54:15
    0 29 44
  • java double保留一位小数:How to Round a Double to One Decimal Place in

    示例示例使用类可以轻松实现java double保留一位小数的功能,具体代码如下:// 创建对象…

    2023-05-14 07:40:03
    0 45 44
  • linux如何写c语言一个完整的指南

    示例示例在Linux系统中,可以使用C语言编写源代码文件,然后使用GCC编译器来编译源代码文件,生成可执行文件。下面是一个简单的C语言代码示例:…

    2023-05-16 02:02:45
    0 48 29

发表评论

登录 后才能评论

评论列表(41条)