如何向 Python plt.title 添加变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43757820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:22:57  来源:igfitidea点击:

How to add a variable to Python plt.title?

pythonpython-3.xmatplotlib

提问by JoeHymanJessieJames

I am trying to plot lots of diagrams, and for each diagram, I want to use a variable to label them. How can I add a variable to plt.title?For example:

我正在尝试绘制大量图表,对于每个图表,我想使用一个变量来标记它们。如何将变量添加到plt.title?例如:

import numpy as np
import matplotlib.pyplot as plt

plt.figure(1)
plt.ylabel('y')
plt.xlabel('x')

for t in xrange(50, 61):
    plt.title('f model: T=t')

    for i in xrange(4, 10):
        plt.plot(1.0 / i, i ** 2, 'ro')

    plt.legend
    plt.show()

In the argument of plt.title(), I want tto be variable changing with the loop.

在 的参数中plt.title(),我想t随着循环而变化。

回答by DavidG

You can change a value in a string by using %. Documentation can be found here.

您可以使用 更改字符串中的值%。文档可以在这里找到

For example:

例如:

num = 2
print "1 + 1 = %i" % num # i represents an integer

This will output:

这将输出:

1 + 1 = 2

1 + 1 = 2

You can also do this with floats and you can choose how many decimal place it will print:

您也可以使用浮点数来执行此操作,并且您可以选择要打印的小数位数:

num = 2.000
print "1.000 + 1.000 = %1.3f" % num # f represents a float

gives:

给出:

1.000 + 1.000 = 2.000

1.000 + 1.000 = 2.000

Using this in your example to update tin the figure title:

在您的示例中使用它来更新t图标题:

plt.figure(1)
plt.ylabel('y')
plt.xlabel('x')

for t in xrange(50,61):
    plt.title('f model: T=%i' %t)

    for i in xrange(4,10):
        plt.plot(1.0/i,i**2,'ro')

    plt.legend
    plt.show()

回答by thewaywewere

You can use print formatting.

您可以使用打印格式。

  1. plt.title('f model: T= {}'.format(t))or
  2. plt.title('f model: T= %d' % (t))# c style print
  1. plt.title('f model: T= {}'.format(t))或者
  2. plt.title('f model: T= %d' % (t))# c 风格打印

回答by RandomUser123

You can also just concatenate the title string:

您也可以只连接标题字符串:

x=1
y=2
plt.title('x= '+str(x)+', y = '+str(y))

will make the title look like

将使标题看起来像

x= 1, y = 2

x= 1, y = 2