Pandas 按降序绘制 x 或 index_column

Pandas plot x or index_column in descending order

我想根据从化学分析中导入的 csv 文件做一些绘图。所以我导入如下:

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

很好看。

按照惯例,我使用 x 轴按降序绘制此类数据。右边的最高数字(不要问我为什么)。所以我重新排序索引列:

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

太棒了!

In [96]:

df2.plot()
Out[96]:

但是当我绘制时它看起来一样 (/sadpanda)

有什么想法 =)?

将索引设为字符串索引 - 然后 plot 会将其视为分类数据,并按照它在数据框中出现的顺序绘制。

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

另一种方法是在 matplotlib 中反转 x 轴的方向。这里代码的关键位是plt.gca().invert_xaxis()。注意:这将 x 轴保留为整数轴。示例代码如下:

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