Reputation: 460
I have been trying to plot values stored in lists as dict values but I have gotten stuck. Heres an example of the structure of the dictionary and my code to iterate over die keys and values:
import matplotlib.pyplot as plt
mydict = {
"A":
[1.0, 0.75, 0.0, 0.25, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.5],
"B":
[1.0, 0.0, 0.0, 0.0, 0.5, 0.6666666666666666, 0.0],
"C":
[0.6666666666666666, 0.3333333333333333, 0.75, 0.25, 0.0, -1, 0.5, 0.75, 0.0, 0.0, 0.0],
"D":
[0.0, 0.0, 0.0, 0.2]}
for k, v in mydict.iteritems():
plt.title('Some data for unit: ' + k)
plt.xlabel('Number of data points')
plt.ylabel('Some unit')
plt.figure(k)
xs = range(0, len(v))
ys = v
plt.plot(xs, ys, '-.')
plt.show
Im a relative beginner and I probably missed something basic and essential, but the following always happens: The first plot comes out empty with the title for unit A and the last one has no title or labels. So Im guessing it mocks up an empty plot for Unit A, plots data for Unit A in the second plot, Unit B in plot three and so forth until the fifth plot, which I did not expect to be there, considering my dict only has four key value pairs.
What am I missing here? Ive tried for hours and just cant come up with a solution.
Many thanks!
Upvotes: 2
Views: 2479
Reputation: 2468
You create a new plot by giving a title. After that that you call plt.figure(k)
, creating another new plot. This is the plot where the data of the current loop will be plotted in. In the next loop you give this plot a new title. That's why everything seems shifted.
Move plt.figure(k)
to the top of the loop. You can also just call plt.figure()
if you don't care about the number of the figure, which -- in most cases -- you don't.
Also plt.show
just refers to the function, but you need to call it: plt.show()
Upvotes: 1
Reputation: 339160
You want to create the figure plt.figure()
before giving it a title. Then you need to decide if you want to show all figures at once (plt.show()
outside the loop), or one-by-one (inside the loop). But, make sure to actually call plt.show()
- mind the ()
.
for k, v in mydict.iteritems():
plt.figure(k)
plt.title('Some data for unit: ' + k)
plt.xlabel('Number of data points')
plt.ylabel('Some unit')
xs = range(0, len(v))
ys = v
plt.plot(xs, ys, '-.')
plt.show()
Upvotes: 2