Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas plot x or index_column in descending order

I wanted to do some plots based on imported csv files from a chemical analysis. So I import as follows:

In [91]:

df = pd.read_csv('/file_location/Untitled 1.csv', delimiter = '\;', index_col = 'IR')
df

Out[91]:
Sample 1    Sample 2
IR      
300 1   0
400 5   4
500 6   0
600 0   8
4 rows × 2 columns



 In [98]:

df.plot()

Fine looks good.

By convention this type of data i plotted with the x axis in descending order. Highest number to the right (do not ask me why). So i reorder the index-col:

In [97]:

df2 = df.sort_index(axis=0, ascending=False, kind='quicksort')
df2
Out[97]:
Sample 1    Sample 2
IR      
600 0   8
500 6   0
400 5   4
300 1   0
4 rows × 2 columns

Awesome!

In [96]:

df2.plot()
Out[96]:

But when i Plot it looks the same (/sadpanda)

Any ideas =)?

like image 981
Sszon Avatar asked Apr 08 '15 10:04

Sszon


People also ask

How do you sort index in descending order?

The sort_index() is used to sort index in ascending and descending order. If you won't mention any parameter, then index sorts in ascending order.

How do I sort a column in descending order in pandas?

In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.

How do I reorder index in pandas?

Import the Pandas module. Create a DataFrame. Drop some rows from the DataFrame using the drop() method. Reset the index of the DataFrame using the reset_index() method.

How do you sort in descending order the entire DataFrame by the title series?

4. Sort Series in Descending Order. To sort the above series in descending order, use the sort_values() function with ascending=False .


1 Answers

Another approach would be to invert the direction of the x-axis in matplotlib. The key bit of code here is plt.gca().invert_xaxis(). Note: this leaves the x-axis as an integer axis. Example code follows:

from StringIO import StringIO # for python 2.7; import from io for python 3
import pandas as pd
import matplotlib.pyplot as plt 

# get data
data = """,sample1, sample2
300, 1,   0
400, 5,   4
500, 6,   0
600, 0,   8"""    
df = pd.read_csv(StringIO(data), header=0, index_col=0, skipinitialspace=True)

# and plot
df.plot()
plt.gca().invert_xaxis()
plt.show()
like image 55
Mark Graph Avatar answered Nov 10 '22 00:11

Mark Graph