添加覆盖 twinx 轴线条的图例

2024-04-29

我有这个Python代码。

  1. 它与轴成对ax并在两个轴上绘制一些函数
  2. 我将图例绘制在ax1

问题是图例没有覆盖曲线ax2

有可能自动定位传说中的ax通过覆盖线ax2.

请注意,在fig.legend选项loc="best"不可用。 我需要在绘图区域内自动定位。

Tnx

import matplotlib.pyplot as plt
import numpy as np

# Set the x values for the sine and cosine functions
x = np.linspace(0, 2*np.pi, 100)

# Create the figure and an axis
fig, ax = plt.subplots()
ax2 = ax.twinx()

# Plot the sine and cosine functions on the axis
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')

ax2.plot(x, np.cos(x+1), label='Cosine 2', color="red")
ax2.plot(x, x, label='Cosine 2', color="green")

# Add a title and labels to the axis
ax.set_title('Sine and Cosine Functions')
ax.set_xlabel('X')
ax.set_ylabel('Y')

# Get the line legends from the axis
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()

# Add a legend to the figure
ax.legend(lines + lines2, labels + labels2, framealpha=1.0)
ax.get_legend().set_zorder(10)

# Display the plot
plt.show()

下面是代码的输出:


参考:

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html https://matplotlib.org/stable/gallery/misc/zorder_demo.html https://matplotlib.org/stable/gallery/misc/zorder_demo.html

The zorder of a legend默认是最高的,所以如果你想要的话,不需要修改它legend在一切之上。

选项1:

您可以通过以下方式完成此任务Figure对象而不是Axes对象与plt.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left').

选项2:

或者您可以将图例设置为ax2代替ax with ax2.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left')。这将返回与选项 1 相同的结果。

import matplotlib.pyplot as plt
import numpy as np

# Set the x values for the sine and cosine functions
x = np.linspace(0, 2 * np.pi, 100)

# Create the figure and an axis
fig, ax = plt.subplots()
ax2 = ax.twinx()

# Plot the sine and cosine functions on the axis
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')

ax2.plot(x, np.cos(x + 1), label='Cosine 2', color="red")
ax2.plot(x, x, label='Cosine 2', color="green")

# Add a title and labels to the axis
ax.set_title('Sine and Cosine Functions')
ax.set_xlabel('X')
ax.set_ylabel('Y')

# Get the line legends from the axis
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()

# Add a legend to the figure
plt.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower left')

# Display the plot
plt.show()

结果 (loc='lower left' and loc='lower center'):

Updated:

参考:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.twinx.html https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.twinx.html

对于我之前的答案中的选项 2,我将第 36 行编辑为ax2.legend(lines + lines2, labels + labels2, framealpha=1.0, loc='lower right')和第 43 行到ax22.legend(lines1 + lines22, labels1 + labels22, framealpha=1.0, loc='lower left')在您新提供的代码中。

如果您有多个子图,请使用Axes对象更加灵活。

现在可以正常工作了:

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

添加覆盖 twinx 轴线条的图例 的相关文章

随机推荐

  • 输出bash脚本的结果

    例如 如果我选择运行一个 bash 脚本 该脚本将输出 回显 时间 例如CheckDate sh 我如何从 Java 运行它 然后在我的 Java 程序中打印 bash 脚本的结果 日期 试试这个代码 String result null
  • 如何使用本地aar依赖?

    我谷歌了一下本地aar 每个人都说它可以工作 但它在android studio 1 1 0上不起作用 我尝试使用 compile fileTree dir libs include aar 但它提示 Warning Project app
  • 如何在 NSBundle 中从 Assets.car(xcassets 的编译版本)加载图像? (不使用 CocoaPods)

    我们收到以下类型的错误消息 无法加载从标识符为 com company OurResourceBundle 的包中的笔尖引用的 iconStatus 图像 基本上 我们将一堆图像放在 xcassets 文件夹中 适用于非捆绑加载的情况 xc
  • 使用 NSJSONSerialization 解析 JSON:错误 3840 - 数据损坏?

    我读过很多关于这个问题的问答 但找不到适合我情况的答案 我从用 PHP 创建的 REST 服务检索 JSON 响应 这是我的代码 NSURLResponse response nil NSError theError1 nil NSErro
  • 需要一种方法来防止不需要的作业参数传播到 Spring Boot 批处理作业的下一次执行

    我正在使用 Spring Boot 2 1 2 和 Spring Batch 4 1 1 运行批处理应用程序 该应用程序使用 MySQL 数据库作为 Spring Batch 元数据数据源 首先 我使用以下命令运行作业 java jar t
  • 随机数列表 - arc4random

    我想创建一个 0 9 的数字数组并希望它们是随机的 意思是 当用户单击 UIButton 时 它会创建一个由对象 4 5 8 3 6 2 9 1 7 0 组成的 NSMutableArray 当用户再次单击该按钮时 它会生成另一个 0 9
  • 自动将 Linux 文件名重命名为 Windows 中合法的新文件名

    我想将 linux 文件重命名为在 windows 中合法的文件名 它的长度不应超过允许的长度 并且不应包含 Windows 中不允许的字符 有时我将论文的标题复制到文件名 它们有特殊字符 例如 or 另外 从 pdf 中复制和粘贴标题时
  • 如何在highcharts中设置动态数据

    我正在从 servlet 获取数据 我从 servlet 发送的 json 对象的 sysout 是 jsonArray bugzilla 20 redmind 14 现在我的java脚本是
  • 单击“提交”按钮时禁用中继器中的选中复选框

    我想在用户单击 ASP NET 中的 提交 按钮时禁用选中的复选框 我可以使用 JavaScript 使用按钮的 onclick 事件禁用复选框 这些复选框位于中继器中 通过单击 提交 按钮提交表单时 代码隐藏按钮单击代码中没有任何复选框显
  • Doxygen 在子目录中找不到标头

    我正在使用 Doxygen 记录 C 库的头文件 在里面Doxyfile 我定义 INPUT include 希望 Doxygen 能够为所有头文件生成文档include Foo 但事实并非如此 只有index html被生成 我可以设置I
  • 绘制从节点到空的箭头

    我想绘制一个美人鱼图 其中包含不与节点连接的箭头 graph LR A Sample Text gt A A gt B B gt A B gt gt A and B gt 失败 可能是因为箭头需要输入和输出节点 有解决方法吗 我可以使节点不
  • 设置样式缩放级别 openlayers 3

    在 Openlayers 中 可以根据缩放级别打开或关闭某些功能 尽管查看了文档 但我在 OpenLayers 3 中没有找到相同的功能 有谁知道如何做到这一点 这是我放置在地图上的功能ol style Text是我只想在用户放大到特定缩放
  • 运算符“&&”不能应用于“bool”和“System.Collections.Generic.IEnumerable”类型的操作数

    我正在尝试第一个过滤器列表 然后使用OrderBy但我收到以下错误Where clause 运算符 不能应用于 bool 类型的操作数并且 System Collections Generic IEnumerable 我的查询有什么问题吗
  • 使用 javascript 打开文件,客户端

    在我的应用程序中 我想打开客户端计算机上存在的文件 我创建了两个应用程序 桌面应用程序和 Web 应用程序 当用户安装桌面应用程序时 一些文件会被复制到其安装路径 我想通过 javascript 从我的 Web 应用程序打开这些文件 出于安
  • AngularJS:使用 $http.post 传递复杂的 json 数据

    我在使用 http post 在 angularjs 中传递复杂的 json 对象时遇到问题 我不断收到从服务器发回的 400 bad request 错误 表示该请求在语法上不正确 我相信它与数组有关 因为当我不包含它时它会很好地传递 我
  • 直接放置在 std::map 中

    为什么这段代码无法编译 std map
  • 有没有办法使用 iframe api 在暂停时隐藏相关的 Youtube 视频?

    我正在使用 iframe API 我想在页面上嵌入一些视频 但我不想在用户暂停视频时显示相关视频 我知道 2018 年 9 月之后 Youtube 取消了在结束或暂停视频时隐藏相关视频的可能性 我知道参数 rel 0 现在显示来自视频上传者
  • Android 检测 Kitkat 的 USB 存储 (4.4)

    我创建了一个 webview 应用程序 它在资产目录中的应用程序内托管一个网站 我想通过插入我的平板电脑 USB 插槽的 U 盘来更新网站 我首先尝试使用 MEDIA MOUNTED 广播 该广播不适用于我的 android 4 4 药片
  • Android SQLite 列.....不是唯一的

    我在 Android 上使用 SQLite 并收到此错误 02 11 18 05 37 224 E SQLiteDatabase 26583 android database sqlite SQLiteConstraintException
  • 添加覆盖 twinx 轴线条的图例

    我有这个Python代码 它与轴成对ax并在两个轴上绘制一些函数 我将图例绘制在ax1 问题是图例没有覆盖曲线ax2 有可能自动定位传说中的ax通过覆盖线ax2 请注意 在fig legend选项loc best 不可用 我需要在绘图区域内