如果要在轴上绘制水平线,也可以尝试方法。您需要指定 y 位置和 xmin 和 xmax 在数据坐标中(即,您在x轴中的实际数据范围)。示例代码段为:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 21, 200)
y = np.exp(-x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')
plt.show()
上面的摘要将在轴上绘制 y = 0.2 的水平线。水平线从 x = 4 开始,以 x = 20 结束。生成的图像为:
If you want to draw a horizontal line in the axes, you might also try ax.hlines() method. You need to specify y position and xmin and xmax in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 21, 200)
y = np.exp(-x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')
plt.show()
The snippet above will plot a horizontal line in the axes at y=0.2. The horizontal line starts at x=4 and ends at x=20. The generated image is:
import seaborn as sns
# sample data
fmri = sns.load_dataset("fmri")
# max y values for stim and cue
c_max, s_max = fmri.pivot_table(index='timepoint', columns='event', values='signal', aggfunc='mean').max()
# plot
g = sns.lineplot(data=fmri, x="timepoint", y="signal", hue="event")
# x min and max
xmin, ymax = g.get_xlim()
# vertical lines
g.hlines(y=[c_max, s_max], xmin=xmin, xmax=xmax, colors=['tab:orange', 'tab:blue'], ls='--', lw=2)
” 。
每个轴都必须通过
import seaborn as sns
# sample data
fmri = sns.load_dataset("fmri")
# used to get the max values (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", style="event", kind="line")
# iterate through the axes
for ax in g.axes.flat:
# get x min and max
xmin, xmax = ax.get_xlim()
# 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].max()
# add horizontal lines
ax.hlines(y=[c_max, s_max], xmin=xmin, xmax=xmax, 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
# get test data; the Date index is already downloaded as 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
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')
# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')
ax.legend()
plt.show()
If you're a plotting a figure with something like fig, ax = plt.subplots(), then replace plt.hlines or plt.axhline with ax.hlines or ax.axhline, respectively.
import seaborn as sns
# sample data
fmri = sns.load_dataset("fmri")
# max y values for stim and cue
c_max, s_max = fmri.pivot_table(index='timepoint', columns='event', values='signal', aggfunc='mean').max()
# plot
g = sns.lineplot(data=fmri, x="timepoint", y="signal", hue="event")
# x min and max
xmin, ymax = g.get_xlim()
# vertical lines
g.hlines(y=[c_max, s_max], xmin=xmin, xmax=xmax, colors=['tab:orange', 'tab:blue'], ls='--', lw=2)
Seaborn figure-level plot
Each axes must be iterated through
import seaborn as sns
# sample data
fmri = sns.load_dataset("fmri")
# used to get the max values (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", style="event", kind="line")
# iterate through the axes
for ax in g.axes.flat:
# get x min and max
xmin, xmax = ax.get_xlim()
# 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].max()
# add horizontal lines
ax.hlines(y=[c_max, s_max], xmin=xmin, xmax=xmax, colors=['tab:orange', 'tab:blue'], ls='--', lw=2, alpha=0.5)
Time Series Axis
xmin and xmax will accept a date like '2020-09-10' or datetime(2020, 9, 10)
import pandas_datareader as web # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt
# get test data; the Date index is already downloaded as 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
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')
# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')
ax.legend()
plt.show()
Sample time series data if web.DataReader doesn't work.
Note that bar plot tick locations have a zero-based index, regardless of the axis tick labels, so select xmin and xmax based on the bar index, not the tick label.
ax.get_xticklabels() will show the locations and labels.
import pandas as pd
import seaborn as sns # for tips data
# load data
tips = sns.load_dataset('tips')
# histogram
ax = tips.plot(kind='hist', y='total_bill', bins=30, ec='k', title='Histogram with Horizontal Line')
_ = ax.hlines(y=6, xmin=0, xmax=55, 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.hlines(y=6, xmin=3, xmax=15, colors='r')
annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')
#####horizontal line
horiz_line_data = np.array([40 for i in xrange(len(xs))])
plt.plot(xs, horiz_line_data, 'r--')
###########plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()
希望解决问题!
You are correct, I think the [0,len(xs)] is throwing you off. You'll want to reuse the original x-axis variable xs and plot that with another numpy array of the same length that has your variable in it.
annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')
#####horizontal line
horiz_line_data = np.array([40 for i in xrange(len(xs))])
plt.plot(xs, horiz_line_data, 'r--')
###########plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
from matplotlib.ticker import LinearLocator
# your data here
annual = np.arange(1,21,1)
l = np.random.random(20)
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
# plot your data
plt.plot(xs,spl(xs),'b')
# horizental line?
ax = plt.axes()
# three ticks:
ax.yaxis.set_major_locator(LinearLocator(3))
# plot grids only on y axis on major locations
plt.grid(True, which='major', axis='y')
# show
plt.show()
You can use plt.grid to draw a horizontal line.
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
from matplotlib.ticker import LinearLocator
# your data here
annual = np.arange(1,21,1)
l = np.random.random(20)
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
# plot your data
plt.plot(xs,spl(xs),'b')
# horizental line?
ax = plt.axes()
# three ticks:
ax.yaxis.set_major_locator(LinearLocator(3))
# plot grids only on y axis on major locations
plt.grid(True, which='major', axis='y')
# show
plt.show()
发布评论
评论(7)
使用
axhline
axhline 线)。例如,这绘制了y = 0.5
的水平线:Use
axhline
(a horizontal axis line). For example, this plots a horizontal line aty = 0.5
:如果要在轴上绘制水平线,也可以尝试 方法。您需要指定
y
位置和xmin
和xmax
在数据坐标中(即,您在x轴中的实际数据范围)。示例代码段为:上面的摘要将在轴上绘制
y = 0.2
的水平线。水平线从x = 4
开始,以x = 20
结束。生成的图像为:If you want to draw a horizontal line in the axes, you might also try
ax.hlines()
method. You need to specifyy
position andxmin
andxmax
in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:The snippet above will plot a horizontal line in the axes at
y=0.2
. The horizontal line starts atx=4
and ends atx=20
. The generated image is:使用
matplotlib.pyplot.pyplot.hlines
:seaborn
和pandas.dataframe.plot
生成的图,两者都使用matplotlib
。列表
传递到y
参数来绘制多个水平线。y
可以作为单个位置传递:y = 40
y
可以作为多个位置传递:y = [39,40 ,41]
matplotlib.axes。 axes.hlines
对于面向对象的API。Fig> ax = plt.subplots()
之类的图形,则替换plt.hlines
或plt.axhline
带有ax.hlines
或ax.axhline
。matplotlib.pyplotlib.pyplot.axhline ;
matplotlib.axes.axes.axes.axes.axes.axhline.axhline
y = 40
),“代码> plt.plot
“在此处输入映像
>
” 。
时间序列轴
xmin
和xmax
将接受像'2020-09-10'
这样的日期代码>或DateTime(2020,9,10)
来自DateTime Import DateTime
xmin = dateTime(2020,9,10),xmax = dateTime(2020,9,10) + TIMEDELTA(天= 3)
date = df.index [9]
,xmin = date,xmax = date + pd.timedelta(days = 3)
,其中索引为a <代码> dateTimeIndex 。dateTime dtype
。 If using pandas, then usepd.to_datetime
< /a>。有关数组或列表,请参阅将Numpy的字符串转换为dateTime 或 或分别转换为日期python 。web.datareader
不起作用。BARPLOT和直方图
Xmin
和xmax
基于条索引而不是tick标签。ax.get_xticklabels()
将显示位置和标签。Use
matplotlib.pyplot.hlines
:seaborn
andpandas.DataFrame.plot
, which both usematplotlib
.list
to they
parameter.y
can be passed as a single location:y=40
y
can be passed as multiple locations:y=[39, 40, 41]
matplotlib.axes.Axes.hlines
for the object oriented api.fig, ax = plt.subplots()
, then replaceplt.hlines
orplt.axhline
withax.hlines
orax.axhline
, respectively.matplotlib.pyplot.axhline
&matplotlib.axes.Axes.axhline
can only plot a single location (e.g.y=40
).vlines
plt.plot
ax.plot
Seaborn axis-level plot
Seaborn figure-level plot
Time Series Axis
xmin
andxmax
will accept a date like'2020-09-10'
ordatetime(2020, 9, 10)
from datetime import datetime
xmin=datetime(2020, 9, 10), xmax=datetime(2020, 9, 10) + timedelta(days=3)
date = df.index[9]
,xmin=date, xmax=date + pd.Timedelta(days=3)
, where the index is aDatetimeIndex
.datetime dtype
. If using pandas, then usepd.to_datetime
. For an array or list, refer to Converting numpy array of strings to datetime or Convert datetime list into date python, respectively.web.DataReader
doesn't work.Barplot and Histograms
xmin
andxmax
based on the bar index, not the tick label.ax.get_xticklabels()
will show the locations and labels.除了这里最受欢迎的答案外,在
plot
pandas> pandas 'sdataframe
dataframe 上调用 plot 之后,还可以链条axhline
>。In addition to the most upvoted answer here, one can also chain
axhline
after callingplot
on apandas
'sDataFrame
.您是正确的,我认为
[0,Len(XS)]
正在抛弃您。您将需要重复使用原始的X轴变量XS
,并使用具有带有您的变量的另一个长度的Numpy数组来绘制它。希望解决问题!
You are correct, I think the
[0,len(xs)]
is throwing you off. You'll want to reuse the original x-axis variablexs
and plot that with another numpy array of the same length that has your variable in it.Hopefully that fixes the problem!
对于那些总是忘记命令
axhline
的人来说,这是一种很好而简单的方法,是您的情况下的以下方式
xs = x
和y = 40
。如果Len(x)很大,那么这将变得降低,您应该真正使用
axhline
。A nice and easy way for those people who always forget the command
axhline
is the followingIn your case
xs = x
andy = 40
.If len(x) is large, then this becomes inefficient and you should really use
axhline
.您可以使用
plt.grid
绘制水平线。You can use
plt.grid
to draw a horizontal line.