Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib generating strange y-axis on certain data sets?

I am writing a python 2.7 script that generates multiple matplotlib graphs in a loop.

import matplotlib.pyplot as plt
import numpy as np

Here I scale the data so the first point is 100

scalefac = 100/float(sdata[0])
for dat in range(len(sdata)):
    sdata[dat] = float(sdata[dat])*scalefac

Then plot it.

y = sdata
x = np.arange(0, len(sdates))

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
aaa = tuple(sdates)
ax.scatter(x,y)
ax.plot(x,y)
plt.xticks(x,aaa)

plt.xlabel('date of run (mm/dd/yy)')
plt.ylabel('power % of baseline')
plt.title('Power Estimation Over Time')
plt.grid(True)
plt.savefig("dump/graph.%s.png" % str(dirlist[d])) 
plt.close(fig)

This seems to work correctly, but only when the y data is not too close together. For instance, when y is [100, 95] or [100, 100, 110] the y axis has the right units and the points are in the right places. When y is [100,100] or [100, 100.5] the y axis is on units of .1 and the data is plotted at ~.2

If it goes through the loop twice and one is [100, 95] and the other is [100, 100.5], only the [100, 95] will get plotted correctly.

Bad graph:

bad graph

Good graph:

good graph

What the heck?

like image 756
Jacob Read Avatar asked Aug 09 '16 16:08

Jacob Read


1 Answers

If I understand you correctly the problem is the offset, e.g. 0.0002 + 9.9998e1, which you want to be plotted as 100, right? If so this answer might help you.

If you think it's too long to read, here is a quick code example. The key thing is ax.get_yaxis().get_major_formatter().set_useOffset(False), which turns off the formatting of the y-values.

import matplotlib.pyplot as plt
import numpy as np

x = [0, 1, 2]
y = [100, 100, 100.1]

fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)

#  The bad plot
ax.scatter(x,y)
ax.plot(x,y)

# The good plot
ax2.scatter(x,y)
ax2.plot(x,y)
ax2.get_yaxis().get_major_formatter().set_useOffset(False)

plt.show()

enter image description here

like image 65
pathoren Avatar answered Oct 06 '22 01:10

pathoren