如何在pyplot中自动标注最大值

2024-04-26

我试图弄清楚如何自动注释图形窗口中的最大值。我知道您可以通过手动输入 x,y 坐标来注释您想要使用的任何点来完成此操作.annotate()方法,但我希望注释是自动的,或者自己找到最大值点。

到目前为止,这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import Series, DataFrame

df = pd.read_csv('macrodata.csv') #Read csv file into dataframe
years = df['year'] #Get years column
infl = df['infl'] #Get inflation rate column

fig10 = plt.figure()
win = fig10.add_subplot(1,1,1)
fig10 = plt.plot(years, infl, lw = 2)

fig10 = plt.xlabel("Years")
fig10 = plt.ylabel("Inflation")
fig10 = plt.title("Inflation with Annotations")

If x and y是要绘制的数组,您可以通过以下方式获得最大值的坐标

xmax = x[numpy.argmax(y)]
ymax = y.max()

这可以合并到一个函数中,您可以简单地用您的数据调用该函数。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-2,8, num=301)
y = np.sinc((x-2.21)*3)


fig, ax = plt.subplots()
ax.plot(x,y)

def annot_max(x,y, ax=None):
    xmax = x[np.argmax(y)]
    ymax = y.max()
    text= "x={:.3f}, y={:.3f}".format(xmax, ymax)
    if not ax:
        ax=plt.gca()
    bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
    arrowprops=dict(arrowstyle="->",connectionstyle="angle,angleA=0,angleB=60")
    kw = dict(xycoords='data',textcoords="axes fraction",
              arrowprops=arrowprops, bbox=bbox_props, ha="right", va="top")
    ax.annotate(text, xy=(xmax, ymax), xytext=(0.94,0.96), **kw)

annot_max(x,y)


ax.set_ylim(-0.3,1.5)
plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在pyplot中自动标注最大值 的相关文章

  • Django:如何从管理界面调用管理自定义命令执行?

    参考 从代码执行管理命令 https stackoverflow com questions 907506 how can i call a custom django manage py command directly from a t
  • Keras AttributeError:“顺序”对象没有属性“predict_classes”

    我试图按照本指南找到模型性能指标 F1 分数 准确性 召回率 https machinelearningmastery com how to calculate precision recall f1 and more for deep l
  • Pytorch“展开”等价于 Tensorflow [重复]

    这个问题在这里已经有答案了 假设我有大小为 50 50 的灰度图像 在本例中批量大小为 2 并且我使用 Pytorch Unfold 函数 如下所示 import numpy as np from torch import nn from
  • 如何读取 10 位原始图像?其中包含 RGB-IR 数据

    我想知道如何从我的 10 位原始 它有 rgb ir 图像数据 数据中提取 RGB 图像 如何使用 Python 或 MATLAB 进行阅读 拍摄时的相机分辨率为 1280x720 室内照片图片下载 https drive google c
  • 登录 python + mod_wsgi 应用程序

    我在 apache 服务器上部署了一个 python Flask 应用程序 这是我的abc conf file WSGIDaemonProcess voting app threads 5 WSGIScriptAlias election
  • 冻结(.exe)一个traitsUI程序,现实可行吗?

    我正在尝试使用 cx freeze 或 pyInstaller 冻结一个 TraitsUI 程序 该程序利用 Chaco Traits TraitsUI 以及较小程度的 mayavi 实际上可以取出 我需要它在 mac linux ubun
  • Python 2to3 Windows CMD

    我已经安装了 python 32 包到 C python32 我还设置了路径 Python 路径 C Python32 Lib C Python32 DLLs C Python32 Lib lib tk 路径 C Python32 我想使用
  • 如何以编程方式关闭wx.DirDialog?

    我有 wxpython 应用程序 可以在单击按钮时打开 wx DirDialog dlg wx DirDialog self Choose a directory style wx DD DEFAULT STYLE if dlg ShowM
  • 如何在 Django 中创建多选框?

    我正在尝试创建多选框字段来自姜戈选择 2 https github com applegrew django select2库如下图所示 我使用了下一个代码 但它返回简单的选择多个小部件 我想我忘了补充一些东西 我的错误在哪里 有人可以告诉
  • 将 csv 写入谷歌云存储

    我试图了解如何将多行 csv 文件写入谷歌云存储 我只是没有遵循文档 https googlecloudplatform github io google cloud python stable storage blobs html hig
  • 是否可以将 SpaCy 安装到 Raspberry Pi 4 Raspbian Buster

    我一整天都在安装 SpaCy sudo pip install U spacy Looking in indexes https pypi org simple https www piwheels org simple Collectin
  • 单个函数的 Numpy 均值和方差?

    使用 Numpy Python 是否可以从单个函数调用返回均值 AND 方差 我知道我可以单独做它们 但是计算样本标准差需要平均值 因此 如果我使用单独的函数来获取均值和方差 则会增加不必要的开销 我尝试在这里查看 numpy 文档 htt
  • TensorFlow - 为什么这个 softmax 回归没有学到任何东西?

    我的目标是用 TensorFlow 做大事 但我正在尝试从小事做起 我有一些小的灰度方块 有一点噪音 我想根据它们的颜色对它们进行分类 例如 3 个类别 黑色 灰色 白色 我编写了一个小 Python 类来生成正方形和 1 hot 向量 并
  • Python 中的延迟求值/惰性求值

    我想延迟对类实例的成员函数的调用的评估 直到该实例实际存在 最小工作示例 class TestClass def init self variable 0 self variable 0 variable 0 def get variabl
  • 使用 PyODBC 选择表中的列名

    我正在编写一个 Python 程序 该程序使用 PyODBC 从 Microsoft Access mdb 文件中选择一些数据 我需要发现几个不同表的列名 在 SQL Server 中 这可以通过使用类似的查询来完成 SELECT c na
  • 如何从已安装的云端硬盘文件夹中永久删除?

    我编写了一个脚本 在每次迭代后将我的模型和训练示例上传到 Google Drive 以防发生崩溃或任何阻止笔记本运行的情况 如下所示 drive path drive My Drive Colab Notebooks models if p
  • mpld3图,注释问题

    我正在使用 mpld3 在 Intranet 网站上显示图形 我正在使用将图形保存到字典并使用 mpld3 js 在客户端渲染它的选项 除非我想使用注释 否则该图呈现良好 这些显然是抵消的 我不明白为什么 因为即使我将偏移量设置为 0 0
  • Python二进制数据读取

    urllib2 请求接收二进制响应 如下所示 00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41 97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47 0
  • Python 装饰器只是语法糖? [复制]

    这个问题在这里已经有答案了 可能的重复 了解 Python 装饰器 https stackoverflow com questions 739654 understanding python decorators 我对使用 Python 装
  • 无法比较类型“ndarray(dtype=int64)”和“str”

    Example of data that I want to replace 数据具有以下属性 购买 V 高 高 中 低 维持 V 高 高 中 低 门 2 3 4 5 更多 2 4人以上 lug boot 小 中 大 安全性低 中高 这就是

随机推荐