matplotlib: fail to plot line or bar; valid axes

时间:2015-07-28 16:20:24

标签: python numpy matplotlib plot

I'm attempting generate matplotlib images through a loop. I have two iterations of loops that generate images. The first loop works, the second doesn't. The axes are valid, I can see that when I print the numpy arrays.

plt_mean = float(week_occurrences) / len(x_axis)
y_np = np.array(y_axis)
std_d = np.std(y_np)
plt.plot(x_axis, y_np, color='#758AA8')
plt.axis([y_axis[0], y_axis[6], 0, int(y_max * 1.2)])
plt.axhline(plt_mean, color='black')
plt.ylabel("Events")
plt.xlabel("Day")
plt.title(event)
plt.savefig("tmp/{} {}.jpg".format(event, y_axis[0]), bbox_inches='tight')
plt.clf()

print(event)
print(y_max)
print(plt_mean)
print(x_axis)
raw_input(y_np)

output:

A user account was changed.
384
111.571428571
[5, 22, 4, 384, 363, 3, 0]
[166 167 168 169 170 171 172]

enter image description here

What am I missing? Why won't it plot the associated lines?

2 个答案:

答案 0 :(得分:1)

I believe the line is plotted, but I think your axis limits are wrong. I'm not entirely sure what you're trying to do, because it looks like you've inverted your x and y.

here is the result after the line:

plt.plot(x_axis, y_np, color='#758AA8')

enter image description here

However, after the line

plt.axis([y_axis[0], y_axis[6], 0, int(y_max * 1.2)])

the axes limit do not make any sense anymore and you're seeing a region where there are no data. plt.axis() takes its argument in the order [xmin, xmax, ymin, ymax]

答案 1 :(得分:1)

Looks like you didn't define y_max correctly. This works for me:

import numpy as np
import matplotlib.pylab as plt

x_axis = [5, 22, 4, 384, 363, 3, 0]
y_axis = [166, 167, 168, 169, 170, 171, 172]
y_max = np.max(y_axis)
event = np.str('A user account was changed.')
week_occurrences = 780.999999997
plt_mean = float(week_occurrences) / len(x_axis)
y_np = np.array(y_axis)
std_d = np.std(y_np)
plt.plot(x_axis, y_np, color='#758AA8')
plt.axis([y_axis[0], y_axis[6], 0, int(y_max * 1.2)])
plt.axhline(plt_mean, color='black')
plt.ylabel("Events")
plt.xlabel("Day")
plt.title(event)
# plt.savefig("tmp/{} {}.jpg".format(event, y_axis[0]), bbox_inches='tight')
# plt.clf()

print(event)
print(y_max)
print(plt_mean)
print(x_axis)