在给定的图上绘制一条水平线

2024-12-24 08:55:00
admin
原创
117
摘要:问题描述:如何向现有图中添加水平线?解决方案 1:使用axhline(水平轴线)。例如,在 处绘制一条水平线y = 0.5:import matplotlib.pyplot as plt plt.axhline(y=0.5, color='r', linestyle='-') plt.show() 解决方案 ...

问题描述:

如何向现有图中添加水平线?


解决方案 1:

使用axhline(水平轴线)。例如,在 处绘制一条水平线y = 0.5

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

示例图

解决方案 2:

如果您想在轴上绘制一条水平线,您也可以尝试ax.hlines()方法。您需要在数据坐标中指定y位置和xminxmax即 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。生成的图像为:

在此处输入图片描述

解决方案 3:

使用matplotlib.pyplot.hlines

  • 这些方法适用于用seaborn和生成的图pandas.DataFrame.plot,它们都使用matplotlib

  • list通过将 a 传递给参数来绘制多条水平线y

  • y可以作为单个位置传递:y=40

  • y可以作为多个位置传递:y=[39, 40, 41]

  • matplotlib.axes.Axes.hlines适用于面向对象的 API。

    • 如果您要绘制类似于的图形fig, ax = plt.subplots(),则分别将plt.hlines或替换plt.axhlineax.hlinesax.axhline

  • matplotlib.pyplot.axhline&matplotlib.axes.Axes.axhline只能绘制单个位置(例如y=40

  • 有关垂直线的信息,请参阅此答案.vlines

plt.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(6, 3))
plt.hlines(y=39.5, xmin=100, xmax=175, colors='aqua', linestyles='-', lw=2, label='Single Short Line')
plt.hlines(y=[39, 40, 41], xmin=[0, 25, 50], xmax=[len(xs)], colors='purple', linestyles='--', lw=2, label='Multiple Lines')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

在此处输入图片描述

ax.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6))

ax1.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
ax1.set_title('One Line')

ax2.hlines(y=[39, 40, 41], xmin=0, xmax=len(xs), colors='purple', linestyles='--', lw=2)
ax2.set_title('Multiple Lines')

plt.tight_layout()
plt.show()

在此处输入图片描述

Seaborn 轴级图

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 图形级绘图

  • 每个轴必须迭代

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)

在此处输入图片描述

时间序列轴

  • xmin并将接受类似或的xmax日期'2020-09-10'`datetime(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),其中索引是DatetimeIndex

  • 轴上的日期列必须是datetime dtype。如果使用 pandas,则使用pd.to_datetime。对于数组或列表,请分别参阅将 numpy 字符串数组转换为 datetime或将 datetime 列表转换为 date python。

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

在此处输入图片描述

  • 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:00'): {'High': 3479.15, 'Low': 3349.63}, pd.Timestamp('2020-09-08 00:00:00'): {'High': 3379.97, 'Low': 3329.27}, pd.Timestamp('2020-09-09 00:00:00'): {'High': 3424.77, 'Low': 3366.84}, pd.Timestamp('2020-09-10 00:00:00'): {'High': 3425.55, 'Low': 3329.25}, pd.Timestamp('2020-09-11 00:00:00'): {'High': 3368.95, 'Low': 3310.47}, pd.Timestamp('2020-09-14 00:00:00'): {'High': 3402.93, 'Low': 3363.56}, pd.Timestamp('2020-09-15 00:00:00'): {'High': 3419.48, 'Low': 3389.25}, pd.Timestamp('2020-09-16 00:00:00'): {'High': 3428.92, 'Low': 3384.45}, pd.Timestamp('2020-09-17 00:00:00'): {'High': 3375.17, 'Low': 3328.82}, pd.Timestamp('2020-09-18 00:00:00'): {'High': 3362.27, 'Low': 3292.4}, pd.Timestamp('2020-09-21 00:00:00'): {'High': 3285.57, 'Low': 3229.1}, pd.Timestamp('2020-09-22 00:00:00'): {'High': 3320.31, 'Low': 3270.95}, pd.Timestamp('2020-09-23 00:00:00'): {'High': 3323.35, 'Low': 3232.57}, pd.Timestamp('2020-09-24 00:00:00'): {'High': 3278.7, 'Low': 3209.45}, pd.Timestamp('2020-09-25 00:00:00'): {'High': 3306.88, 'Low': 3228.44}, pd.Timestamp('2020-09-28 00:00:00'): {'High': 3360.74, 'Low': 3332.91}}

df = pd.DataFrame.from_dict(data, 'index')

条形图和直方图

  • 请注意,无论轴刻度标签如何,条形图刻度位置都有一个从零开始的索引,因此请根据条形索引(而不是刻度标签)
    xmin进行选择。xmax

    • ax.get_xticklabels()将显示位置和标签。

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

在此处输入图片描述

在此处输入图片描述

解决方案 4:

除了这里获得最多赞同的答案之外,还可以axhline在调用aplot后进行链接。pandas`DataFrame`

import pandas as pd

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

在此处输入图片描述

解决方案 5:

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

希望可以解决问题!

解决方案 6:

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

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

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

解决方案 7:

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

随机数据图示例

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用