Pandas plot x or index_column in descending order

霸气de小男生 提交于 2019-12-14 01:37:07

问题


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 =)?


回答1:


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



回答2:


Make the index a string index - then plot will treat it as categorical data, and plot in the order it appears in the dataframe.

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

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)

# string index
df.index = df.index.astype(str)

# reverse dataframe
df = df[::-1]

# plot
df.plot()
plt.show()


来源:https://stackoverflow.com/questions/29511645/pandas-plot-x-or-index-column-in-descending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!