pandas 熊猫按降序绘制 x 或 index_column
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29511645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas plot x or index_column in descending order
提问by Sszon
I wanted to do some plots based on imported csv files from a chemical analysis. So I import as follows:
我想根据从化学分析中导入的 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()
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:
按照惯例,我用 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
Awesome!
惊人的!
In [96]:
df2.plot()
Out[96]:
But when i Plot it looks the same (/sadpanda)
但是当我绘制它时它看起来是一样的 (/sadpanda)
Any ideas =)?
任何想法=)?
回答by Mark Graph
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:
另一种方法是在 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()
回答by Mark Graph
Make the index a string index - then plot will treat it as categorical data, and plot in the order it appears in the dataframe.
使索引成为字符串索引 - 然后 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()

