【问题标题】:Create dynamic footnote text in matplotlib在 matplotlib 中创建动态脚注文本
【发布时间】:2020-05-04 21:49:33
【问题描述】:

我希望能够在 matplotlib 中添加类似于以下内容的脚注文本:

以下代码将创建具有相似文本的绘图

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


fig, ax = plt.subplots(figsize = (5, 8))
n = 10
np.random.seed(1)
_ = ax.scatter(np.random.randint(0, 10, n), np.random.randint(0, 10, n), s=500)
x = 0
y = 1
_ = ax.text(
    x, y, "hello this is some text at the bottom of the plot", fontsize=15, color="#555"
)

看起来像:

但是,如果数据发生变化,则上述不会调整,例如:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


fig, ax = plt.subplots(figsize=(5, 8))

n = 10
np.random.seed(2)
_ = ax.scatter(np.random.randint(0, 10, n), np.random.randint(0, 10, n), s=500)
x = 0
y = 1
_ = ax.text(
    x, y, "hello this is some text at the bottom of the plot", fontsize=15, color="#555"
)

我有seen this question/answer,这只是说明如何在特定的x,y 坐标处绘制文本。我特别希望能够设置一个脚注,而不是在特定的 x,y 处绘制,所以解决方案应该是动态的。

另外,使用 OOP 接口作为mentioned in the docs 是首选。

注意 - 使用fig.tight_layout()时当前的建议似乎有问题

【问题讨论】:

  • 附带说明,如果您不需要ax.scatterax.text 的返回值,则根本不需要将它们分配给变量。
  • @mapf 我已经为你添加了导入 - 而且 - 我知道我不需要它们,我只是分配它们,所以我不会在 jupyterlab 中得到输出

标签: python numpy matplotlib plot


【解决方案1】:

您应该尝试使用transform=ax.transAxes 相对于子图而不是相对于子图中的点来绘制文本。您还应该设置对齐方式,以便文本根据您想要的位置开始。可以玩弄点位置。

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


fig, ax = plt.subplots(figsize=(5, 8))

n = 10
np.random.seed(2)
_ = ax.scatter(np.random.randint(0, 10, n), np.random.randint(0, 10, n), s=500)
x = 0
y = -.07
ax.text(x, y, "hello this is some text at the bottom of the plot", fontsize=15, 
        horizontalalignment='left',verticalalignment='top', transform=ax.transAxes)

plt.show()

【讨论】:

  • 这在使用fig.tight_layout()时好像有问题
  • 你需要fig.tight_layout()吗?您正在调整轴,因此您选择的数字没有相同的含义。见matplotlib.org/3.1.1/api/tight_layout_api.html
  • 在绘制文本之前还是之后更改布局?
猜你喜欢
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2016-05-09
  • 2012-09-01
  • 2018-07-28
  • 1970-01-01
相关资源
最近更新 更多