Skip to content

Instantly share code, notes, and snippets.

@aizquier
Created November 11, 2016 18:48
Show Gist options
  • Save aizquier/975b450481c4d7f12f207c8b5f35ec5c to your computer and use it in GitHub Desktop.
Save aizquier/975b450481c4d7f12f207c8b5f35ec5c to your computer and use it in GitHub Desktop.
Matplotlib: plot the legend outside the plot and adjusts the viewport to contain the plot and the (outer) legend
# * just prepares some data to plot, the legend trick is at line 54
docs = {'ndocs': {'Actes': 1775,
'Article': 626,
'Autre': 497580,
'Compte rendu': 1831,
'Culturel': 76034,
'Document': 525,
'Livres': 313,
'Note': 126,
'Rapport recherche': 2,
'Thèse': 790}, 'sumdocs': 907822}
dt = ['Actes', 'Article', 'Autre', 'Compte rendu', 'Culturel', 'Document', 'Livres', 'Note', 'Rapport recherche', 'Thèse']
def Markers():
def colors_g():
while True:
for c in ('b','g','r','c', 'm', 'y', 'k'):
yield c
def patterns_g():
while True:
for m in ( 's', 'p', '*', 'h', 'H', 'd','o', 'D', 'v', '^', '<', '>'):
yield m
colors = colors_g()
patterns = patterns_g()
while True:
yield (next(patterns), next(colors))
for w in range(4):
#w -= 1
marker_gen = Markers()
ndocs = [(docs['ndocs'][_m]/docs['sumdocs']) * 100 for _m in dt]
nhits = [(data[w]['doc_types'][_m]/data[w]['hits'])* 100 for _m in dt]
plt.plot(np.linspace(0,70), np.linspace(0,70), linestyle='--', color='k')
l = []
lt = []
for _m in range(len(dt)):
marker = next(marker_gen)
leg = plt.scatter([ndocs[_m]], [nhits[_m]], marker=marker[0], color=marker[1], s=40, edgecolor='black', linewidth=1, alpha=0.5)
l.append(leg)
lt.append(dt[_m])
# * plots the legend outside the plot and adjusts the viewport to contain the plot and the (outer) legend
plt.title("Query: %d words" % (w+1))
plt.legend(l, lt, bbox_to_anchor=(1.05, 1), loc=2) # * trick here: bbox_to_anchor parameter
plt.xlabel("Total")
plt.ylabel("Queries")
plt.tight_layout(rect = [0, 0, 0.7, 1])
plt.savefig("queries_vs_all_%d_words.pdf" % (w+1), format="pdf", bbox_inches = 'tight') # * trick here: bbox_inches = 'tight' parameter
#plt.savefig("queries_vs_all_%d_words.png" % (w+1))
plt.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment