Reputation: 609
I am new to matplotlib
(I usually use R for graphics), so I don't know everything, but can I format legend as table? For example I have this picture, where formating was done by hand. I have idea of something akin to latex formating, where I could specify aligning of each row, put the colored box in the top line of every sub cell and not in the middle of it. Does matplotlib have support for it? Even with usage of latex.
Upvotes: 0
Views: 1149
Reputation: 6389
Something like this:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
x1 = np.random.normal(0, 0.2, 1000)
x2 = np.random.uniform(low=-0.5, high=0.5, size=1000)
fig, ax = plt.subplots()
ax.hist(x1, bins=20, histtype='stepfilled', normed=1, stacked=True, color='orange')
ax.hist(x2, bins=20, histtype='stepfilled', normed=1, color='purple')
# legend text
f1_label = 'Before:\n 4699 names\n 284 languages'
f2_label = 'After:\n 4337 names\n 235 languages\n 14 duplicates\n 49 languages not found'
# defines legend symbol as rectangular patch with color and label as indicated
f1_leg = mpatches.Patch(color='orange', label=f1_label)
f2_leg = mpatches.Patch(color='purple', label=f2_label)
leg = plt.legend(handles=[f1_leg, f2_leg], fancybox=True, loc=1)
# not noticable here but useful if legend overlaps data
leg.get_frame().set_alpha(0.45)
plt.ylim([0, 3.5])
plt.show()
EDIT: The plot above was made with matplotlib v1.4.3 (in Anaconda). I also have an older version of matplotlib (1.3.1) where this code does not display the legend. This code will work on 1.3.1:
import matplotlib.pyplot as plt
import numpy as np
x1 = np.random.normal(0, 0.2, 1000)
x2 = np.random.uniform(low=-0.5, high=0.5, size=1000)
fig, ax = plt.subplots()
# legend text
f1_label = 'Before:\n 4699 names\n 284 languages'
f2_label = 'After:\n 4337 names\n 235 languages\n 14 duplicates\n 49 languages not found'
ax.hist(x1, bins=20, histtype='stepfilled', normed=1, stacked=True, color='orange', label=f1_label)
ax.hist(x2, bins=20, histtype='stepfilled', normed=1, stacked=True, color='purple', label=f2_label)
leg = plt.legend(fancybox=True, loc=1)
leg.get_frame().set_alpha(0.45)
plt.ylim([0, 3.2])
plt.show()
Upvotes: 1