我正在使用matplotlib
绘制一些直方图。正如您在图像中看到的那样,我的图形被标签覆盖。
我尝试以下方法:
plt.figure(num=None, figsize=(10, 8),
dpi=180, facecolor='w', edgecolor='k')
但实际上增加了整个窗口仍然没有显示图表。我该如何解决?
答案 0 :(得分:1)
有时,缩小图例的大小(特别是标签的字体大小)不是一种选择。例如,双柱纸的单列图就是这种情况。
在您的特定情况下,我会:
下面是一个示例,向您展示如何做到这一点:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
plt.close('all')
fig = plt.figure()
ax = fig.add_axes([0.15, 0.15, 0.80, 0.80])
#---- generate some data ----
x = np.arange(-10, 10, 0.001)
y1 = norm.pdf(x, 0, 5.2)
y2 = norm.pdf(x, 0, 5)
y3 = norm.pdf(x, 0, 2)
#---- setup ticks ----
ax.tick_params(axis='both', direction='out', top='off', right='off')
#---- set axes labels ----
ax.set_ylabel('Log (frequency)', labelpad=15, fontsize=14)
ax.set_xlabel('Image values', labelpad=15, fontsize=14)
#---- plot data ----
h1, = ax.plot(x, y1, color='blue', lw=1.5)
h2, = ax.plot(x, y2, dashes=[2, 3], color='green', lw=2)
h3, = ax.plot(x, y3, dashes=[1.5, 5, 10, 5], color='red', lw=1.5)
#---- plot legend ----
lines = [h1, h2, h3]
labels = ['Transformed input image', 'Reference image', 'Input image']
ax.legend(lines, labels, bbox_to_anchor=(0, 1), loc='upper left', ncol=1,
fontsize=14, labelspacing=0.5, borderaxespad=0.5, frameon=False,
handletextpad=1, numpoints=1)
#---- set axis limits ----
ax.axis(ymax=0.22)
#---- show and save ----
plt.show(block=False)
fig.savefig('legend_overlap.png')
上面的代码导致:
但是,如果您仍想在图例周围保留一个框架,您还可以使用图形宽度和高度之间的比例,直到图例适合图形。这可以如下例所示完成:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
plt.close('all')
fwidth = 10
fheight = 5
fig = plt.figure(figsize=(fwidth, fheight))
left_margin = 1.1 / fwidth
right_margin = 0.25 / fwidth
bottom_margin = 0.75 / fheight
top_margin = 0.25 / fheight
#---- generate an axe ----
h = 1 - (bottom_margin + top_margin)
w = 1 - (left_margin + right_margin)
ax = fig.add_axes([left_margin, bottom_margin, w, h])
#---- generate some data ----
x = np.arange(-10, 10, 0.001)
y1 = norm.pdf(x, 0, 5.2)
y2 = norm.pdf(x, 0, 5)
y3 = norm.pdf(x, 0, 2)
#---- setup ticks ----
ax.tick_params(axis='both', direction='out', top='off', right='off')
#---- set axes labels ----
ax.set_ylabel('Log (frequency)', labelpad=15, fontsize=14)
ax.set_xlabel('Image values', labelpad=15, fontsize=14)
#---- plot data ----
h1, = ax.plot(x, y1, color='blue', lw=1.5)
h2, = ax.plot(x, y2, dashes=[2, 3], color='green', lw=2)
h3, = ax.plot(x, y3, dashes=[1.5, 5, 10, 5], color='red', lw=1.5)
#---- plot legend ----
lines = [h1, h2, h3]
labels = ['Transformed input image', 'Reference image', 'Input image']
ax.legend(lines, labels, loc='upper right', ncol=1, fancybox=True,
fontsize=14, labelspacing=0.5, handletextpad=1, numpoints=1)
#---- set axis limits ----
ax.axis(ymax=0.22)
#---- show and save ----
plt.show(block=False)
fig.savefig('legend_overlap_alternate.png')
结果是:
答案 1 :(得分:0)