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:

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 t to be variable changing with the loop.

推荐答案

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

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

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

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()

Python-3.x相关问答推荐

海象表达可以放在方括号中而不是括号中吗?

为什么vs code返回错误—LocaleError:int对象没有属性where,但相同的代码运行在Google Colab上没有任何问题''''

如何绘制交叉验证的AUROC并找到最佳阈值?

如何使用Python将嵌套的XML转换为CSV

按一列分组,如果日期列相同,则在数字列中填写缺少的值

在循环中使用Print&S结束参数时出现奇怪的问题

如何将值映射到具有上限和下限的新列

Pandas 窗口聚合两个排序表

如何对具有多个列值的 pandas 数据框进行数据透视/数据透视表

DynamoDB - boto3 - batch_write_item:提供的关键元素与架构不匹配

将两列合并为一列,将它们制成字典 - pandas - groupby

使用大型多个数据集,其中每个数据集包含多个值 - Pytorch

在不使用字符串方法的情况下查找字符串最后一个单词的长度 - Python

如何在 Spyder 控制台中使用变量执行 Python 3.3 脚本?

Pylint 给我最后的新行丢失

创建集合的 Python 性能比较 - set() 与 {} 文字

python 3的蓝牙库

混合全局/参数和名为top的函数的奇怪python行为

python中的绝对导入是什么?

如何使用 Celery 和 Django 将任务路由到不同的队列