2

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 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

Code:

 import pandas as pd
 df = pd.Dataframe('mydata')
 df.plot()

Link of ploted graph: http://bayanbox.ir/id/7161086291332750314?view

I don't know have to put value like '2609.703' in yticks instead of what shown in graph

Moradi
  • 133
  • 2
  • 7

2 Answers2

3

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:

import matplotlib.pyplot as plt

data = [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)
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
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 in data ])

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).

DrV
  • 22,637
  • 7
  • 60
  • 72