How to add a variable to Python plt.title?

后端 未结 3 1183
生来不讨喜
生来不讨喜 2020-12-29 04:27

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:

相关标签:
3条回答
  • 2020-12-29 05:13

    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

    0 讨论(0)
  • 2020-12-29 05:26

    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()
    
    0 讨论(0)
  • 2020-12-29 05:27

    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
    0 讨论(0)
提交回复
热议问题