shadowprice
shadowprice

Reputation: 647

Bar Graph with Legend without Colors

I need to plot a bar graph of data with labels that are too long to fit as ticks on the x-axis. I was hoping to include the labels in the legend, but cannot figure out to remove the color from the legend (including the color makes the legend cluttered). Below is some sample code:

import matplotlib.pyplot as plt

data_dic={1:'1:Text 1',2:'2:Text 2',3:'3:Text 3',4:'4:Text 4'}
ax1 = plt.subplot(111)
xval = [1,2,3,4]
yval = [ 22.,  13.,  21.,   6.]
for j in range(len(xval)):
    ax1.bar(xval[j], yval[j], width=0.8, bottom=0.0, align='center', color='k', label=data_dic[xval[j]])
ax1.set_xticks(xval)
ax1.legend()
plt.show()

enter image description here

Thanks!

Upvotes: 0

Views: 2931

Answers (2)

tom10
tom10

Reputation: 69182

Setting handlength=0 gets you close. One trick though, is that even then the edge is drawn, so you need to set a transparent edge color for the marker. Also adjust the handletextpad so the text is well centered in the legend box. For example, replace your legend line with the following:

H, L = ax1.get_legend_handles_labels()
p = Rectangle((0, 0), 1, 1, fc='r', ec=(1, 0, 0, 0))
ax1.legend([p]*4, L, handlelength=0, handletextpad=0)

enter image description here

Upvotes: 1

Molly
Molly

Reputation: 13610

You can create a legend that doesn't show the color or any marker by making a plot with no markers or lines and associating the labels with that plot. Here's how it works with your example:

import matplotlib.pyplot as plt

data_dic={1:'1:Text 1',2:'2:Text 2',3:'3:Text 3',4:'4:Text 4'}
ax1 = plt.subplot(111)
xval = [1,2,3,4]
yval = [ 22.,  13.,  21.,   6.]
for j in range(len(xval)):
    ax1.bar(xval[j], yval[j], width=0.8, bottom=0.0, align='center', color='k')
    ax1.plot(1,1,label = data_dic[xval[j]],marker = '',ls ='') #plot with not marker or line
ax1.set_xticks(xval)
ax1.legend(frameon = False)
plt.show()

legend with no markers

You could also use text instead of legend since you don't need the text associated with markers.

Upvotes: 1

Related Questions