Python 使用 matplotlib 绘制水平线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33382619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:16:13  来源:igfitidea点击:

Plot a horizontal line using matplotlib

pythonmatplotlib

提问by Ibe

I have used spline interpolation to smooth a time series and would also like to add a horizontal line to the plot. But there seems to be an issue that is out of my grips. Any assistance would be really helpful. Here is what I have:

我已经使用样条插值来平滑时间序列,并且还想在图中添加一条水平线。但似乎有一个问题超出了我的掌握。任何帮助都会非常有帮助。这是我所拥有的:

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

problem seems to be with my use of [0,len(xs)]for horizontal line plotting.

问题似乎与我[0,len(xs)]对水平线绘图的使用有关。

采纳答案by chill_turner

You are correct, I think the [0,len(xs)]is throwing you off. You'll want to reuse the original x-axis variable xsand plot that with another numpy array of the same length that has your variable in it.

你是对的,我认为这[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()

Hopefully that fixes the problem!

希望能解决问题!

回答by BlivetWidget

You're looking for axhline(a horizontal axis line). The following will give you a horizontal line at y = 0.5, for example.

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

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

sample figure

样图

回答by MosteM

A nice and easy way for those people who always forget the command axhlineis the following

对于那些总是忘记命令的人来说,一个简单而简单的方法axhline是以下

plt.plot(x, [y]*len(x))

In your case xs = xand y = 40. If len(x) is large, then this becomes inefficient and you should really use axhline.

在你的情况xs = xy = 40. 如果 len(x) 很大,那么这会变得效率低下,您应该真正使用axhline.

回答by jdhao

If you want to draw a horizontal line in the axes, you might also try ax.hlines()method. You need to specify yposition and xminand xmaxin the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:

如果你想在轴上画一条水平线,你也可以尝试ax.hlines()方法。您需要在数据坐标(即 x 轴中的实际数据范围)中指定y位置和xminxmax。示例代码片段是:

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=4and ends at x=20. The generated image is:

上面的代码片段将在坐标区中绘制一条水平线y=0.2。水平线从 开始到x=4结束x=20。生成的图像是:

enter image description here

在此处输入图片说明

回答by ayorgo

In addition to the most upvoted answer here, one can also chain axhlineafter calling ploton a pandas's DataFrame.

除了这里最受好评的答案外,您还可以axhline在调用plota 后链接pandas's DataFrame

import pandas as pd

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

enter image description here

在此处输入图片说明

回答by Mehdi

You can use plt.gridto draw a horizontal line.

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

random data plot example

随机数据图示例

回答by Trenton McKinney

Use matplotlib.pyplot.hlines

matplotlib.pyplot.hlines

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
plt.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
plt.show()

enter image description here

在此处输入图片说明