1

I've been trying to figure out how to output two metrics to a chart I'm trying to display. I looked around on here and found that the way to do this was via the plt.text

I've tried about 80 different variations and I still can't get it to ouput.

This is my latest code:

mae = metrics.mean_absolute_error(y_test,y_pred)
mse = metrics.mean_squared_error(y_test, y_pred)
y_df = pd.DataFrame(index=pd.to_datetime(test_index))
y_pred = y_pred.reshape(len(y_pred), )
y_test = y_test.reshape(len(y_test), )
y_df['y_pred'] = y_pred
y_df['y_test'] = y_test
y_df.plot(title='{}'.format(gsc.best_estimator_))
plt.text(.5, .5, 'MAE:{}\nMSE:{}'.format(mae, mse))
plt.tight_layout()
plt.show(block=False)
print('end')
plt.show()

My chart will print - but no text. I've tried switching from the pandas matplotlib wrapper and plotting directly with plt.plot but still couldn't get it to run. Any Ideas on what I'm doing wrong?

Edit: I've tried to go away from using the pandas wrapper to plot again. Now i'm getting:

enter image description here

mae = metrics.mean_absolute_error(y_test,y_pred)
mse = metrics.mean_squared_error(y_test, y_pred)
y_df = pd.DataFrame(index=pd.to_datetime(test_index))
y_pred = y_pred.reshape(len(y_pred), )
y_test = y_test.reshape(len(y_test), )
y_df['y_pred'] = y_pred
y_df['y_test'] = y_test
line1 = Line2D(test_index, y_pred,color="goldenrod")
line2 = Line2D(test_index, y_test, color="dodgerblue")
#y_df.plot(title='{}'.format(gsc.best_estimator_))
plt.text(.5, .5, 'MAE:{}\nMSE:{}'.format(mae, mse))
plt.tight_layout()
plt.show(block=False)
print('end')
plt.show()
novawaly
  • 1,051
  • 3
  • 12
  • 27
  • 1
    The problem is likely the coordinates of the text. We don't know your dataframe (please consider [mcve]), but most likely `(.5, .5)` is simply way outside the data limits of the plot. – ImportanceOfBeingErnest Jun 21 '19 at 19:33
  • @ImportanceOfBeingErnest What if i just want to put it in a legend? Would that be better practice? Is there a way to do that? – novawaly Jun 21 '19 at 19:36

2 Answers2

2

I'm not sure why but your code works on my laptop with matplotlib 3.1.0. Maybe you could consider reinstalling matplotlib.

import matplotlib.pyplot as plt

mae, mse = 1, 1
plt.plot()  # in your case : plt.plot(test_index, y_pred,color="goldenrod")
plt.text(.5, .5, 'MAE:{}\nMSE:{}'.format(mae, mse))
plt.tight_layout()
plt.show(block=False)
plt.show()

Regarding the Edit: creating Line2D objects like that will not link anything to the actual plot. You can either directly use

plt.plot(test_index, y_pred,color="goldenrod") 
plt.plot(test_index, y_test, color="dodgerblue")
plt.show()

or

fig, ax = plt.subplots()
line1 = Line2D(test_index, y_pred,color="goldenrod")
line2 = Line2D(test_index, y_test, color="dodgerblue")
ax.add_line(line1)
ax.add_line(line2)
plt.show()

Adding text with AnchoredText outside frame

from matplotlib.offsetbox import AnchoredText
at = AnchoredText("My Text",
                   loc='lower left', frameon=True,
                   bbox_to_anchor=(0., 1.),
                   bbox_transform=ax.transAxes  # or plt.gca().transAxes
                   )
plt.gca().add_artist(at)

play with bbox_to_anchor for position.

2

I'd use AnchoredText to put some text in a corner of the axes.

at = matplotlib.offsetbox.AnchoredText("My Text", loc='upper right', frameon=True)
plt.gca().add_artist(at)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • there it is! my final question would be is there a way to get it to be just outside the plot area instead of on the plot? – novawaly Jun 21 '19 at 19:47
  • Mhh, apparently the system has duplicated my answer :) Anyways, you can use the `bbox_to_anchor` argument to put the text outside the axes. This works the same as for a legend so I would point you to [this answer](https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot/43439132#43439132). – ImportanceOfBeingErnest Jun 21 '19 at 20:00