0

I am trying to get this chart to show the x axis starting at G and ending with A (left to right). The Udemy instructor wrote this exact same code and generated the desired results - my x axis seems backwards....and of course, the instructor has not addressed the question.

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)

enter image description here

BuJay
  • 115
  • 1
  • 12

3 Answers3

2

As far as I understood, you want to get the following graph, right?

graph

If so, then your function seems to work well, just call it at the end of your code:

plot_by_woe(df)
  • Thanks Elena_Kosourova - yes - your results are what I am after. It seems strange. When I call the function, the output I provided is generated- I.e., the order of the x axis is backwards…. – BuJay Jul 19 '21 at 00:29
  • Hi BuJay, the only issue that I noticed in your code above was about function body indentation. So I fixed it, and the code ran well. But I guess it was only the matter of mistyping, otherwise with this issue your code wouldn't run at all. If my answer resolved your problem, do you mind marking it as a solution? Thank you! – Elena_Kosourova Jul 19 '21 at 11:21
  • Hi Elena - I upvoted but didn't mark as solution. It looks like there is a bug - see my post below. Thanks for your help! – BuJay Jul 19 '21 at 12:52
2

All in all, here's my code:

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)
0

Apparently, there is a bug in the matplotlib version I am using ('2.1.2' and earlier)

How to prevent alphabetical sorting for python bars with matplotlib?

I have tried a bunch of workarounds but haven't found a solution yet. At least we have an explanation.

BuJay
  • 115
  • 1
  • 12