38

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.

0

4 Answers 4

40

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()
Sign up to request clarification or add additional context in comments.

Comments

21

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

Comments

20

You can use string formatting.

  1. plt.title('f model: T= {}'.format(t)) or
  2. plt.title('f model: T= %d' % (t)) C style print

Comments

-1

import matplotlib.pyplot as plt

# Daten

bedarf = 515.85

ist_ohne_urlaub = 435.05

ist_mit_urlaub = 359.05

# 1) Diagramm ohne Urlaub

plt.figure()

plt.bar(["Benötigt", "Vorhanden"], [bedarf, ist_ohne_urlaub])

plt.title("Stundenbedarf vs. Stunden vorhanden (ohne Urlaub)")

plt.ylabel("Stunden pro Woche")

plt.ylim(0, bedarf * 1.1) # etwas Platz oberhalb lassen

plt.text(0, bedarf + 5, f"{bedarf:.2f} h")

plt.text(1, ist_ohne_urlaub + 5, f"{ist_ohne_urlaub:.2f} h")

plt.show()

# 2) Diagramm mit 2 Mitarbeitern im Urlaub

plt.figure()

plt.bar(["Benötigt", "Verfügbar (bei Urlaub)"], [bedarf, ist_mit_urlaub])

plt.title("Stundenbedarf vs. verfügbare Stunden (2 MA im Urlaub)")

plt.ylabel("Stunden pro Woche")

plt.ylim(0, bedarf * 1.1)

plt.text(0, bedarf + 5, f"{bedarf:.2f} h")

plt.text(1, ist_mit_urlaub + 5, f"{ist_mit_urlaub:.2f} h")

plt.show()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.