Python 使用matplotlib绘制水平线

Python 使用matplotlib绘制水平线,python,matplotlib,Python,Matplotlib,我使用样条插值来平滑时间序列,还想在绘图中添加一条水平线。但似乎有一个问题超出了我的控制范围。任何帮助都会很有帮助。以下是我所拥有的: 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') plt.plot([0,len(xs)]

我使用样条插值来平滑时间序列,还想在绘图中添加一条水平线。但似乎有一个问题超出了我的控制范围。任何帮助都会很有帮助。以下是我所拥有的:

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')

plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()

问题似乎在于我使用
[0,len(xs)]
进行水平线绘制

你是对的,我认为
[0,len(xs)]
把你甩了。您需要重用原始x轴变量
xs
,并使用另一个长度与您的变量相同的numpy数组绘制该变量

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()
希望这能解决问题

您正在寻找(一条水平轴线)。例如,以下内容将在
y=0.5处为您提供一条水平线:

import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()

对于那些总是忘记使用命令的人来说,下面是一个简单易行的方法

plt.plot(x, [y]*len(x))
在您的情况下,
xs=x
y=40

如果len(x)较大,则效率会降低,您应该真正使用
axhline

如果您想在轴上绘制一条水平线,也可以尝试该方法。您需要在数据坐标中指定
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
。生成的图像是:


除了这里投票最多的答案外,还可以在
熊猫
数据框上调用
plot
后链接
axhline

import pandas as pd

(pd.DataFrame([1, 2, 3])
   .plot(kind='bar', color='orange')
   .axhline(y=1.5));

您可以使用
plt.grid
绘制水平线

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()

使用:
  • 通过将
    列表
    传递到
    y
    参数,绘制多条水平线
  • y
    可以作为单个位置传递:
    y=40
  • y
    可以作为多个位置传递:
    y=[39,40,41]
  • 如果您正在使用类似于
    fig,ax=plt.subplots()
    的图形绘制,则分别将
    plt.hlines
    plt.axhline
    替换为
    ax.hlines
  • 只能绘制单个位置(例如
    y=40
  • 有关垂直线,请参见
plt.plot
将numpy导入为np
将matplotlib.pyplot作为plt导入
xs=np.linspace(1,21200)
plt.图(figsize=(6,3))
plt.hlines(y=39.5,xmin=100,xmax=175,colors='aqua',linestyles='-',lw=2,label='Single Short Line')
plt.hline(y=[39,40,41],xmin=[0,25,50],xmax=[len(xs)],colors='purple',linestyles='--',lw=2,label='Multiple line')
plt.图例(bbox_至_锚=(1.04,0.5),loc=“左中”,borderaxespad=0)

ax.plot
将numpy导入为np
将matplotlib.pyplot作为plt导入
xs=np.linspace(1,21200)
图(ax1,ax2)=plt.子批次(2,1,figsize=(6,6))
ax1.hlines(y=40,xmin=0,xmax=len(xs),colors='r',linestyles=''--',lw=2)
ax1.设置标题(“一行”)
ax2.hlines(y=[39,40,41],xmin=0,xmax=len(xs),colors='purple',linestyles='--',lw=2)
ax2.设置标题(“多行”)
plt.紧_布局()
plt.show()

时间序列轴
  • xmin
    xmax
    将接受类似于
    '2020-09-10'
    日期时间(2020,9,10)
    • 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)
      ,其中索引为
      DatetimeIndex
import pandas_datareader as web#conda或pip安装此程序;不是熊猫的一部分
作为pd进口熊猫
将matplotlib.pyplot作为plt导入
#获取测试数据
df=web.DataReader(“^gspc”,data_source='yahoo',start='2020-09-01',end='2020-09-28')。iloc[:,:2]
#绘图数据帧
ax=df.plot(figsize=(9,6),title='S&P500',ylabel='Price')
#添加水平线
ax.hlines(y=3450,xmin='2020-09-10',xmax='2020-09-17',color='紫色',label='test')
ax.图例()
plt.show()

  • 如果
    web.DataReader
    不工作,则采样时间序列数据
data={pd.Timestamp('2020-09-01 00:00:00'):{'High':3528.03,'Low':3494.6},pd.Timestamp('2020-09-02 00:00:00'):{'High':3588.11,'Low':3535.23},pd.Timestamp('2020-09-03 00:00:00'):{'High':3564.85,'Low':3427.41},pd.Timestamp('2020-09-04 00:00'):{'High':3479.15,'Low':3349.63},pd-09:00'):'{'High':3379.97,'Low':3329.27},pd.时间戳('2020-09-09 00:00:00'):{'High':3424.77,'Low':3366.84},pd.时间戳('2020-09-10 00:00:00'):{'High':3425.55,'Low':3329.25},pd.时间戳('2020-09-11 00:00:00:00:00'):{'High':3368.95,'Low':3310.47},pd.时间戳('2020-09-14:00:00:00'):'High':3329.63,'pd.时间戳,'('2020-09-15 00:00:00'):{'High':3419.48,'Low':3389.25},pd.时间戳('2020-09-16 00:00:00'):{'High':3428.92,'Low':3384.45},pd.时间戳('2020-09-17 00:00:00'):{'High':3375.17,'Low':3328.82},pd.时间戳('2020-09-18 00:00:00'):{'High':3362.27,'Low':3292.4,'时间戳('2020-09-22 00:00:00'):{'High':3320.31',Low':3270.95},时间戳('2020-09-23 00:00:00'):{'High':3323.35',Low':3232.57},时间戳('2020-09-24 00:00:00'):{'High':3278.7',Low':3209.45},时间戳('2020-09-25 00:00'):{'High':3306.88',Low':3228.44},时间戳('2020-09:00:00'){'High':3360.74,'Low':3332.91}
df=pd.DataFrame.from_dict(数据“索引”)
pylab.绘图(…)可以覆盖给定坐标的水平线或垂直线

这是可行的,但效率不是特别高,尤其是当您根据数据创建一个可能非常大的阵列时。如果您打算这样做,使用
import pylab as pl  
import numpy as np

observations = [0.797, 1.116, 1.071, 0.998, -0.333, 1.129, 0.381, 0.815, 1.28715,
    0.727, 1.309147, 2.492, 0.946, 0.486536, 0.382539, -0.482, -0.208923,
    0.981166, 0.499, 0.022, 0.747333, -0.045, 0.27304, -1.386, 0.654258, 
    -0.43931, -2.012764, -0.387, -0.730, 0.812032, -0.229, -0.286, -0.293,
    -0.483649, 0.232185, -0.027, 0.142, 0.173, -0.618, 0.393, 0.534, 0.804,
    -0.867, 0.776, 0.342, 0.797, 0.550, -0.215, 0.706, -0.973] 

targets = [-0.007, -0.029, -0.025, -0.0119, -0.0719, -0.1283, -0.1077, -0.0844, 
    -0.0474, -0.0419, -0.016, 0.0613, 0.0949, 0.0553, 0.0353, 0.0173, 0.0467,
    0.0562, 0.0523, -0.0032, 0.0548, 0.0245, 0.0372, 0.0404, 0.0388, 0.0703,
    0.0203, -0.0078, -0.0102, 0.0151, -0.0048, -0.0027, 0.0215, -0.0063, -0.0216,
    -0.0618, -0.0172, 0.0212, -0.0203, -0.006, 0.0438, 0.0642, 0.0365, 0.0124,
    -0.0332, -0.064, 0.0061, -0.0007, -0.0242, -0.036] 
 
#scatter plot using x and y points.  c stands for color.  s stands for size 
pl.scatter(observations, targets, c='red', s=5.5) 
 
max_feature_float = max(observations) 
horizontal_line_start_position = 0 
num_dots_on_horizontal_line = 20  
xs = np.linspace(horizontal_line_start_position,max_feature_float, 
    num_dots_on_horizontal_line) 
horiz_line_data = np.array([0 for i in range(len(xs))]) 
pl.plot(xs, horiz_line_data, 'b--') 
 
max_tars_float = max(targets) 
#make a vertical green line starting at (x=0,y=0) and going to (x=0, y=2) ) 
pl.plot((0, 0), (0, max_tars_float), 'g-') 
 
#define the feature and targets axis legend names and title. 
pl.xlabel("observation") 
pl.ylabel("target") 
pl.title('Scatterplot of target against observation.') 
pl.show()