Reputation: 173
I have a Python3.6 code which produces two plots, one with three axis and one with two axes. The plot with three axes has a legend with thin lines.
Unfortunately the second plot legend has lines with thickness equal to the height of the label:
Here is the code for the second figure:
How can I reduce the thickness of the lines in the legend?
It would appear that the code didn't make it to the post.
Here it is:
#two plots on one figure
def two_scales(ax1, time, data1, data2, c1, c2):
ax2 = ax1.twinx()
ax1.plot(time, data1, 'r')
ax1.set_xlabel("Distance ($\AA$)")
ax1.set_ylabel('Atom Charge',color='r')
ax2.plot(time, data2, 'b')
ax2.set_ylabel('Orbital Energy',color='b')
return ax1, ax2
t = data[:,0]
s1 = data[:,3]
s2 = data[:,5]
fig, ax = plt.subplots()
ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')
def color_y_axis(ax, color):
for t in ax.get_yticklabels():
t.set_color(color)
return None
color_y_axis(ax1, 'r')
color_y_axis(ax2, 'b')
plt.title('Molecular Transforms')
patch_red = mpatches.Patch(color='red',label='Atom Charge')
patch_blue = mpatches.Patch(color='blue',label='Orbital Energy')
plt.legend(handles = [patch_red,patch_blue])
plt.draw()
plt.show()
name_plt = name+'-fig2.png'
fig.savefig(name_plt,bbox_inches='tight')
Upvotes: 0
Views: 1402
Reputation: 339650
The usual way to create labels for a legend is to use the label
argument of the artist to show in the legend, ax.plot(...., label="some label")
. Using the actual artist, which has this label set, makes sure the legend shows a symbol wich corresponds to the artist; in case of line plot this would naturally be a line.
import matplotlib.pyplot as plt
time=[1,2,3,4]; data1=[0,5,4,3.3];data2=[100,150,89,70]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
l1, = ax1.plot(time, data1, 'r', label='Atom Charge')
ax1.set_xlabel("Distance ($\AA$)")
ax1.set_ylabel('Atom Charge',color='r')
l2, = ax2.plot(time, data2, 'b', label='Orbital Energy')
ax2.set_ylabel('Orbital Energy',color='b')
ax1.legend(handles=[l1,l2])
plt.show()
Upvotes: 0
Reputation: 5732
Sounds like you want a line for your legend but actually used a patch. Examples and details can be found here. You can use line like this small example:
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
line_red = mlines.Line2D([], [], color='red',label='Atom Charge')
line_blue = mlines.Line2D([], [], color='blue',label='Orbital Energy')
plt.legend(handles = [line_red,line_blue])
plt.show()
Upvotes: 1