Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a variable to Python plt.title?

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.

like image 608
JoeJackJessieJames Avatar asked May 03 '17 10:05

JoeJackJessieJames


People also ask

How do you put a variable in a PLT title?

Create data points for x and y using numpy and num (is a variable) to calculate y and set this in title. Plot x and y data points using plot() method with red color. Set the title of the curve with variable num. To display the figure, use show() method.

How do you add a title to a PLT in Python?

With Pyplot, you can use the title() function to set a title for the plot.

What is the use of Matplotlib in Python explain use of plot () show () and title () functions of Matplotlib?

matplotlib. pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.


3 Answers

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()
like image 99
DavidG Avatar answered Oct 17 '22 02:10

DavidG


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
like image 24
thewaywewere Avatar answered Oct 17 '22 01:10

thewaywewere


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

like image 11
RandomUser123 Avatar answered Oct 17 '22 01:10

RandomUser123