7

I'm reading a pandas dataframe, and trying to generate a plot from it. In the plot, the data points seem to be getting connected in an order determined by ascending y value, resulting in a weird zig-zagging plot like this:

enter image description here

The code goes something like this:

from pandas import DataFrame as df
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

data = df.from_csv(...)

plt.plot(data['COL1'], data['COL2'])

Any suggestions on how to fix the order in which the dots are connected (i.e. connect them in the sequence in which they appear going from left to right on the plot)? Thanks.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Lamps1829
  • 2,231
  • 3
  • 24
  • 32

1 Answers1

5

Is the order of values in COL1 different from the csv?

You can sort by COL1 first, add this before plotting:

data.sort('COL1', inplace=True)
Rutger Kassies
  • 61,630
  • 17
  • 112
  • 97
  • 1
    Thanks - that did work. However, is there a way to do the same with matplotlib's plotting functionality, rather than manipulating the DataFrame itself? It seems that there should be... – Lamps1829 Jul 22 '13 at 12:28
  • 1
    I doubt it, mpl plots the data as it is passed. Since your COL1 is (apparently) not sorted, its not going to happen automatically. Mpl does have a sort function, see `matplotlib.cbook.Sorter()`, but i dont think its more convenient then Pandas. You can sort your df on the fly without modifying the DataFrame: `plt.plot(data.sort('COL1')['COL1'], data.sort('COL1')['COL2'])`. But i would sort on forehand, perhaps store it as a different df if you dont want to modify your original. – Rutger Kassies Jul 22 '13 at 12:46
  • I'd agree that using pandas' sorting functionality does seem preferable to matplotlib's sorter. Thank you! – Lamps1829 Jul 22 '13 at 12:57
  • @RutgerKassies Thank's for the pointer, [matplotlib.cbook.Sorter()](http://matplotlib.org/api/cbook_api.html#matplotlib.cbook.Sorter) is very useful when you don't use pandas, or alternatively a simple native [lambda sorted](http://stackoverflow.com/a/4174956). – gaborous Aug 15 '16 at 22:34