在 matplotlib 中对 x 轴进行排序

DIG*_*SUM 5 python matplotlib pandas

为什么此代码不绘制按“值”排序的 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()
Run Code Online (Sandbox Code Playgroud)

and*_*ece 5

鉴于您选择的变量名称,加上围绕散点图使用的看似混乱,它似乎可能name是您想要在 x 轴上绘制的分类变量,按 排序value

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

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)
Run Code Online (Sandbox Code Playgroud)

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