Issue
Every option I try does not get the legend to show for my plot. Please help. Here's the code and the plot works fine with all my inputs being simple NumPy arrays. When adding the legend function a tiny box appears in the corner so I know that the instruction is running but with nothing in it. I'm using Jupyter Notebook and my other attempts are shown after #
. Can anyone find the flaw:
import pandas as pd
import matplotlib.pyplot as plt
ratios = ['Share Price', 'PEG', 'Price to Sales']
final_z_scores = np.transpose(final_z_scores)
print(final_z_scores)
fig = plt.figure(figsize=(6,4))
#plt.plot(ratios, final_z_scores[0], ratios, final_z_scores[1], ratios, final_z_scores[2])
first = plt.plot(ratios, final_z_scores[0])
second = plt.plot(ratios, final_z_scores[1])
#ax.legend((first, second), ('oscillatory', 'damped'), loc='upper right', shadow=True)
ax.legend((first, second), ('label1', 'label2'))
plt.xlabel('Ratio Types')
plt.ylabel('Values')
plt.title('Final Comparisons of Stock Ratios')
plt.legend(loc='upper left')
plt.plot()
plt.show()
Solution
Calling plt.legend()
without specifying the handles
or labels
explicitly obeys the description of this call signature outlined here:
The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling theset_label()
method on the artist:
So in order to have the legend be automatically populated in your example you simply need to assign labels to the different plots:
import pandas as pd
import matplotlib.pyplot as plt
ratios = ['Share Price', 'PEG', 'Price to Sales']
final_z_scores = np.transpose(final_z_scores)
fig = plt.figure(figsize=(6,4))
first = plt.plot(ratios, final_z_scores[0], label='label1')
second = plt.plot(ratios, final_z_scores[1], label='label2')
plt.xlabel('Ratio Types')
plt.ylabel('Values')
plt.title('Final Comparisons of Stock Ratios')
plt.legend(loc='upper left')
# Calling plt.plot() here is unnecessary
plt.show()
Answered By - William Miller
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.