【问题标题】:How to add a variable to Python plt.title?如何将变量添加到 Python plt.title?
【发布时间】:2017-10-01 03:41:30
【问题描述】:

我正在尝试绘制很多图表,对于每个图表,我想使用一个变量来标记它们。如何将变量添加到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()

plt.title() 的参数中,我希望t 是随循环变化的变量。

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    您可以使用% 更改字符串中的值。文档可以找到here.

    例如:

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

    这将输出:

    1 + 1 = 2

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

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

    给予:

    1.000 + 1.000 = 2.000

    在您的示例中使用它来更新图形标题中的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()
    

    【讨论】:

      【解决方案2】:

      您可以使用打印格式。

      1. plt.title('f model: T= {}'.format(t))
      2. plt.title('f model: T= %d' % (t))#c 样式打印

      【讨论】:

        【解决方案3】:

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

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

        会使标题看起来像

        x= 1, y = 2

        【讨论】:

        • 如果没坏就不要修!
        猜你喜欢
        • 1970-01-01
        • 2012-08-07
        • 2016-11-06
        • 2020-11-22
        • 2019-09-13
        • 1970-01-01
        • 2014-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多