如何将一条水平线添加到现有的绘图中?
当前回答
你可以用plt。网格画一条水平线。
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()
其他回答
对于那些总是忘记命令轴的人来说,下面是一个很好的和简单的方法
plt.plot(x, [y]*len(x))
在这里,xs = x y = 40。 如果len(x)很大,那么这种方法就很低效,你应该使用axhline。
你可以用plt。网格画一条水平线。
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()
使用axhline(水平轴线)。例如,这是一条y = 0.5处的水平线:
import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()
除了这里被点赞最多的答案外,人们还可以在熊猫的数据框架上调用plot后链接axhline。
import pandas as pd
(pd.DataFrame([1, 2, 3])
.plot(kind='bar', color='orange')
.axhline(y=1.5));
如果想在坐标轴上画一条水平线,也可以尝试ax.hlines()方法。您需要指定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结束。生成的图像为:
推荐文章
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?
- 解析.py文件,读取AST,修改它,然后写回修改后的源代码
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件
- 在Python中,使用argparse只允许正整数
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?