我是matplotlib
的新手(我通常使用R表示图形),所以我不知道所有内容,但我可以将图例格式化为表吗?例如,我有this图片,其中格式化是手工完成的。我知道类似于乳胶成型的东西,我可以在其中指定每行的对齐,将彩色框放在每个子单元格的顶行而不是在它的中间。 matplotlib是否支持它?即使使用乳胶。
答案 0 :(得分:1)
这样的事情:
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()
编辑:上图是使用matplotlib v1.4.3(在Anaconda中)制作的。我还有一个旧版本的matplotlib(1.3.1),其中此代码不显示图例。此代码适用于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()