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()
海运轴级图
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)
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)
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()
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()
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, lims=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param lims: Optionally the (xmin, xmax) of the lines
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
if lims is None:
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, lims=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param lims: Optionally the (ymin, ymax) of the lines
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
if lims is None:
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
6条答案
按热度按时间piztneat1#
添加覆盖整个绘图窗口的垂直线而无需指定其实际高度的标准方法是
plt.axvline
或
您可以使用许多可用于其他绘图命令的关键字(例如
color
、linestyle
、linewidth
...)。如果您喜欢坐标轴,可以传入关键字参数ymin
和ymax
(例如ymin=0.25
,ymax=0.75
将覆盖图的中半部分)。水平线(axhline
)和矩形(axvspan
)有相应的函数。hpxqektj2#
matplotlib.pyplot.vlines
对比matplotlib.pyplot.axvline
pandas.DataFrame.plot
生成的图,这两个图都使用matplotlib
。vlines
接受x
的一个或多个位置,而axvline
允许一个位置。x=37
。x=[37, 38, 39]
。vlines
将ymin
和ymax
作为y轴上的位置,而axvline
将ymin
和ymax
作为y轴范围的百分比。vlines
传递多行时,将list
传递给ymin
和ymax
。matplotlib.axes.Axes.vlines
和matplotlib.axes.Axes.axvline
。fig, ax = plt.subplots()
的东西绘制一个图形,那么分别用ax.vlines
或ax.axvline
替换plt.vlines
或plt.axvline
。.hlines
的水平线。海运轴级图
Seaborn图形级图
'region = frontal'
,两个事件的最大值都发生在5
处。条形图
x
。ax.get_xticklabels()
将显示位置和标签。直方图
时序轴
datetime dtype
。如果列或索引的类型不正确,则必须转换为pd.to_datetime
。x
将接受类似'2020-09-24'
或datetime(2020, 9, 2)
的日期。mzmfm0qo3#
对于多行
c3frrgcw4#
要将
legend
和/或colors
添加到某些垂直线,请使用以下命令:结果
jm81lzqq5#
像其他人建议的那样,在循环中调用axvline是可行的,但这可能不方便,因为
1.每一行都是一个单独的情节对象,这会导致当你有很多行的时候速度非常慢。
1.创建图例时,每行都有一个新条目,这可能不是您想要的。
相反,您可以使用以下便利函数将所有线创建为单个绘图对象:
hiz5n14c6#
除了上面答案中提供的
plt.axvline
和plt.plot((x1, x2), (y1, y2))
* 或 *plt.plot([x1, x2], [y1, y2])
之外,还可以使用在
x_pos
处绘制一条从y1
到y2
的垂直线,其中值y1
和y2
是绝对数据坐标。