首页 文章

如何更改绘图的大小并防止y轴重叠?

提问于
浏览
1

我绘制了一个带有大量水平条的水平条形图 . 有什么方法可以阻止 overlapping of the y axis titles and the bars in the bar graphs . 或者唯一的方法是增加图表的高度?我尝试过使用:plt.figure(figsize =(13,14))但是当我尝试用plt.figure替换plt.show()时它也不起作用(figsize =(13,14)) . show()

我收到错误:UserWarning:matplotlib目前正在使用非GUI后端,因此无法显示图"matplotlib is currently using a non-GUI backend, "

import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

length=[477, 531, 568, 651, 1599, 1605, 1635, 1960, 2009, 2446, 2668, 3308, 3433, 3889, 4180, 4529, 5388, 6378, 7588, 7671, 7679, 8505, 8763, 8863, 8910, 9028, 9030, 10124, 10722, 10894, 11103, 11388, 12167, 12464, 14217, 14367, 14472, 16501, 18765, 19407, 19627, 20795, 21727, 21912, 22620, 24871, 25045, 25625, 25867, 27512, 30380, 30424, 31264, 32070, 32277, 33879, 35749, 35932, 37406, 37414, 40040, 42070, 42516, 42804, 44381, 46314, 48216, 48349, 50547, 50796, 53759, 54716, 65888, 81106, 86280, 104522, 179133, 189921]
y_pos = np.arange(len(length))
error = np.random.rand(len(length))
plt.barh(y_pos, length, xerr=error*2, align='center', alpha=0.3)
plt.yticks(y_pos, length)
plt.xlabel('Lengths')
plt.title('Comparison of different cuts')
plt.show()

这是我所指的图:

enter image description here

2 回答

  • 0

    您正在小空间中绘制大量条形图并标记每个刻度线 . 使这个清晰易读的最简单方法是增加绘图的长度 . 立即使用 plt.figure(figsize=(10,20)) 使我的情节清晰可辨 .

    如果你想保持图形相同的大小,你可以调整一些其他的旋钮 . 首先,您可以使用 height 参数控制每个水平条的高度 . 它默认为.8所以尝试使用较低的值 . 您还可以使用 fontsize 参数控制yticks的大小 . 调整这些参数将为您提供不重叠的条形/刻度,但代价是分辨率 . 要在使用 plt.savefig 保存图形时提高分辨率,请使用 dpi 参数将其设置为高于默认值 .

  • 0

    y轴上的标签数量非常多,因此很难将它们全部放入绘图中 . 增加绘图的大小将有所帮助,另一件可能有用的方法是减小y-tick标签的字体大小,如下所示:

    ax = plt.gca()
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(6)
    

    也许你也可以给出所有其他或第三个y-tick标签 .

相关问题