pandas 在 matplotlib 中对 x 轴进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44088240/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:39:08  来源:igfitidea点击:

Sorting the x axis in matplotlib

pythonpandasmatplotlib

提问by DIGSUM

Why does this code not plot the x-axis sorted by 'value'?

为什么此代码不绘制按“值”排序的 x 轴?

import pandas as pd
import matplotlib.pyplot as plt

# creating dataframe
df=pd.DataFrame()
df['name'] = [1,2,3]
df['value'] = [4,3,5]

# sorting dataframe
df.sort_values('value', ascending = False, inplace= True)

# plot
plt.scatter(df['value'],df['name'])
plt.show()

回答by andrew_reece

Given your choice of variable names, plus the seeming confusion surrounding the use of scatter plots, it seems like namemay be a categorical variable that you'd like to plot on the x-axis, sorted by value.

考虑到您对变量名称的选择,加上散点图的使用似乎有些混乱,您似乎想name在 x 轴上绘制一个分类变量,按 排序value

If that's the case, I'd recommend initially plotting with df.indexas the x-axis, and then changing the tick labels to nameentries. Use reset_index()after sort_valuesto get the correct index ordering.

如果是这种情况,我建议最初使用df.indexx 轴进行绘图,然后将刻度标签更改为name条目。使用reset_index()aftersort_values获得正确的索引排序。

Both Pandas and Pyplot should be able to do this without additional modules, but I had some trouble getting tick labels to line up. Instead, I found Seaborn's pointplot()handled this job without any trouble:

Pandas 和 Pyplot 都应该能够在没有额外模块的情况下做到这一点,但是我在让刻度标签对齐时遇到了一些麻烦。相反,我发现 Seabornpointplot()毫不费力地处理了这项工作:

# sort, then reset index
df = df.sort_values('value', ascending = False).reset_index(drop=True)

import seaborn as sns
ax = sns.pointplot(x=df.index, y=df.value)
ax.set_xlabel("Name")
ax.set_ylabel("Value")

# Use name column to label x ticks
_ = ax.set_xticklabels(df.name.astype(str).values)

[1]: https://i.stack.imgur.com/PX

[1]:https://i.stack.imgur.com/PX