为什么此代码不绘制按“值”排序的 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()
最佳答案
考虑到您选择的变量名称,加上散点图的使用似乎很困惑,name
似乎可能是您想要在 x 轴上绘制的分类变量,按值
排序。
如果是这种情况,我建议首先使用 df.index
作为 x 轴进行绘图,然后将刻度标签更改为 name
条目。在 sort_values
之后使用 reset_index()
以获得正确的索引排序。
Pandas 和 Pyplot 都应该能够在没有额外模块的情况下做到这一点,但我在排列刻度标签时遇到了一些麻烦。相反,我找到了 Seaborn 的 pointplot()
毫无困难地处理了这项工作:
# 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)
关于python - 在 matplotlib 中对 x 轴进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44088240/