0

I am trying to retrofit @MaxU's code that they used in this answer here: Making a regression line through a bar char using pandas or seaborn

I am trying to use the same exact concept, but apply it to my horizontal bar plot. I have changed their code as such:

regression_STS = pd.DataFrame({
    "Years": Years,
    "S_scores": S_scores
})

lr = Ridge()
lr.fit(regression_STS[['S_scores']], regression_STS['Years'])
Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,
   normalize=False, random_state=None, solver='auto', tol=0.001)

Here is the plot code:


fig, axes = plt.subplots(nrows=1, ncols=2, sharey=False, sharex=False)
S = axes[0].barh(Years, S_scores, align='center', color=np.where(S_scores < 0, 'red', 'green'))
axes[0].set(title='S Score')
axes[0].set_xlim(-40, 80)
axes[0].plot(regression_STS["S_scores"], lr.coef_*regression_STS['S_scores']+lr.intercept_, color='orange')


rects1 = S.patches

for rect, label in zip(S, S_presidents):
    width = rect.get_width() + 2
    label_y_pos = rect.get_y() + rect.get_height() / 2
    axes[0].text(width, label_y_pos, s=label, color='blue')#, ha="right", va="top")
    

The plot that appears is this: Horizontal Bar Plot

However, the regression line only seems to follow the x axis (the S-scores), but the years. I'd like to have a line that starts at 2000 and goes up to 2020. Any suggestions?

Thank you so much!

zepcron
  • 3
  • 3
  • You probably need to switch x and y for the line plot, and use `Years` for y. `axes[0].plot(lr.coef_*regression_STS['Years']+lr.intercept_, regression_STS["Years"], ..)` – JohanC Sep 27 '21 at 09:01
  • @JohanC thanks for the reply! Unfortunately, I did not see a change with your suggestions. I've tried other combinations too with switching x and y, and Years vs S-Score for y, but only this version seems to get something. – zepcron Oct 03 '21 at 22:04

0 Answers0