【问题标题】:How to properly plot labels in a graph?如何在图表中正确绘制标签?
【发布时间】:2021-12-28 15:47:00
【问题描述】:

我想在 Python 中绘制一个“函数序列”,并在图中绘制函数的相应标签。

我使用 matplotlib,但是,我面临以下问题。

(1)。图表应标注每个函数对应的 $f_n$。

(2)。它必须保存到包含标签的文件中。

这是我的代码:

import matplotlib as mpl
mpl.rc('text', usetex = True) #for LaTex notation in the Plot
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np

plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])

x=np.arange(-1,1,0.001)

for i in range(1,5,1):
    y = 1 - (1 / (1+x**2)**i)
    plt.plot(x,y,label=i)

plt.xlabel('$x$')
plt.ylabel('$y$')

plt.savefig('seqn_of_function1.eps', format='eps', 
dpi=1000)

plt.legend()

plt.show()

这段代码的问题是:

  1. 此代码给出以下输出,但无法保存带有标签的 .eps 文件 (plt.savefig('seqn_of_function1.eps', format='eps', dpi=1000))
  1. 它只标记“i”,但是,我希望它标记为 $f_i$。

我将代码中的行更改为:plt.plot(x,y,label='$f_$',i),但它给出了“invalid_syntax”错误。

【问题讨论】:

  • 您是否尝试过使用plt.plot(x,y,label='f_{}'.format(i))? (而不是plt.plot(x,y,label='$f_$',i)
  • @bene....这给出了一个错误。
  • 还有如何保存带有标签的 .eps 文件?我的代码没有这样做......
  • 我正在调查。标签不会被保存,因为您在创建标签之前保存了图形 (plt.legend()) -> 首先调用 plt.legend(),然后调用 plt.savefig(...)
  • @bene...非常感谢....它已修复.....那么之前的问题呢..??用$f_n$创建标签

标签: python python-3.x


【解决方案1】:

这应该可行:

import matplotlib as mpl

mpl.rc('text', usetex=True)  # for LaTex notation in the Plot
mpl.rc('font', family='serif')

import matplotlib.pyplot as plt
import numpy as np

plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot', 'dark_background'])

x = np.arange(-1, 1, 0.001)

for i in range(1, 5, 1):
    y = 1 - (1 / (1 + x ** 2) ** i)
    plt.plot(x, y, label='$f_{}$'.format(i))

plt.xlabel('$x$')
plt.ylabel('$y$')

plt.legend()

plt.savefig('seqn_of_function1.eps', format='eps', dpi=1000)

plt.show()

【讨论】:

【解决方案2】:

您可以使用 fString 来显示您的标签,如下所示:

plt.plot(x, y, label=f'$f_{i}$')

i 的哪个值在运行时发生变化

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2014-01-19
    • 2021-01-28
    相关资源
    最近更新 更多