How do I add a variable to Python plt.title?

I am trying to plot many charts and for each chart I want to use a variable to label them. How to 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, plt.title()

I want to t

change using a loop.

+3


source to share


3 answers


You can change the value in the string with %

. The 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 float and you can choose how many decimal places 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 title of the figure:

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

      

+3


source


You can use print formatting. In the meantime, there is no need to know about it. ”



  • plt.title('f model: T= {}'.format(t))

    or
  • plt.title('f model: T= %d' % (t))

    # c print style
+1


source


Throw all the plot functions inside the for loop, specifically for the index in the range (number of plots). Use an index in the title of the story for each story. Or, alternatively, subplot.

0


source







All Articles