更改顺序 x 轴 matplotlib

change order x axis matplotlib

我试图让这张图表显示从 G 开始到 A 结束的 x 轴(从左到右)。 Udemy 讲师编写了完全相同的代码并生成了所需的结果 - 我的 x 轴似乎向后......当然,讲师没有解决这个问题。

def plot_by_woe(df, rotation_of_x_axis_labels = 0):
x = df.iloc[:, 0].apply(str)
y = df['WoE']
plt.figure(figsize = (18,6))
plt.plot(x, y, marker='o', linestyle = '--', color = 'k')
plt.xlabel(df.columns[0])
plt.ylabel('Weight of Evidence')
plt.title(str('Weight of Evidence by ' + df.columns[0]))
plt.xticks(rotation = rotation_of_x_axis_labels)

df = pd.DataFrame(
[['G',-1.113459],
 ['F',-0.975440],
 ['E',-0.678267],
 ['D',-0.391843],
 ['C',-0.049503],
 ['B',0.358476],
 ['A',1.107830]],
columns = ['grade', 'WoE'])
df

plot_by_woe(df)

据我了解,你想得到下面的图表,对吧?

graph

如果是这样,那么您的函数似乎运行良好,只需在代码末尾调用它即可:

plot_by_woe(df)

总而言之,这是我的代码:

def plot_by_woe(df, rotation_of_x_axis_labels = 0):
    x = df.iloc[:, 0].apply(str)
    y = df['WoE']
    plt.figure(figsize = (18,6))
    plt.plot(x, y, marker='o', linestyle = '--', color = 'k')
    plt.xlabel(df.columns[0])
    plt.ylabel('Weight of Evidence')
    plt.title(str('Weight of Evidence by ' + df.columns[0]))
    plt.xticks(rotation = rotation_of_x_axis_labels)

df = pd.DataFrame(
[['G',-1.113459],
 ['F',-0.975440],
 ['E',-0.678267],
 ['D',-0.391843],
 ['C',-0.049503],
 ['B',0.358476],
 ['A',1.107830]],
columns = ['grade', 'WoE'])

plot_by_woe(df)

显然,我使用的 matplotlib 版本(“2.1.2”及更早版本)存在错误

How to prevent alphabetical sorting for python bars with matplotlib?

我已经尝试了很多解决方法,但还没有找到解决方案。至少我们有一个解释。