python - Pandas 按降序绘制 x 或 index_column

标签 python pandas ipython

我想根据从化学分析中导入的 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)

有什么想法 =)?

最佳答案

另一种方法是在 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()

关于python - Pandas 按降序绘制 x 或 index_column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29511645/

相关文章:

python - 类型错误: 'range' 对象在没有明显原因的情况下不可调用

python - 多线程 Python 文件系统爬虫

pandas - Polars 相当于 Pandas 中的 .values

ipython - 配置 ipython 以自动使用某些设置,如 doctest_mode on

python - 我用 python 做的测验不起作用

python - 将 RLE 从列表转换为 Python 中的字符串

python - Pandas 在多索引上应用函数

python - 选择 matplotlib 中要绘制的子图

with 语句中的 Python 交互式 REPL

python - 为新样式 ipython (v5) 提示添加颜色