Skip to content Skip to sidebar Skip to footer

Wrong Value In Matplotlib Yticks

I'm trying to plot from pandas dataframe and matplotlib show wrong value in yticks Height data: 2014-08-08 06:00:00 2609.494 2014-08-08 05:45:00 2609.550 2014-08-08 05:30:00 26

Solution 1:

It's not showing incorrect ticks, it's just displaying things relative to an offset value (notice the text at the top of the y-axis). By default, this happens whenever you're displaying large number with very little difference between them.

It easiest to control this using ax.ticklabel_format(...). In your case, you want to specify useOffset=False.

For example:

importmatplotlib.pyplotaspltdata= [2609.494, 2609.55, 2609.605, 2609.658, 2609.703,
        2609.741, 2609.769, 2609.787, 2609.799, 2609.802]

fig,ax=plt.subplots()ax.plot(data)ax.ticklabel_format(useOffset=False)plt.show()

enter image description here

Or, if you're using the plot method of a Pandas DataFrame, its return value is the axes object, so just:

ax = df.plot()
ax.ticklabel_format(useOffset=False)

Solution 2:

The question is about setting the Y tick formatter of the plot

import pandas as pd
import datetime
import matplotlib.ticker

data = [
["2014-08-08 06:00:00",  2609.494],
["2014-08-08 05:45:00",  2609.550],
["2014-08-08 05:30:00",  2609.605],
["2014-08-08 05:15:00",  2609.658],
["2014-08-08 05:00:00",  2609.703],
["2014-08-08 04:45:00",  2609.741],
["2014-08-08 04:30:00",  2609.769],
["2014-08-08 04:15:00",  2609.787],
["2014-08-08 04:00:00",  2609.799],
["2014-08-08 03:45:00",  2609.802]]

df = pd.DataFrame([ [ datetime.datetime.strptime(d[0], "%Y-%m-%d %H:%M:%S"), d[1]] for d indata ])

p = df.plot()
p.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%.1f"))

Creates:

enter image description here

The beef here is on the last two lines, the beginning is just recreating the dataframe. The format string given to the FormatStrFormatter is the C style format string (here one decimal).

Post a Comment for "Wrong Value In Matplotlib Yticks"