Skip to main content
 首页 » 编程设计

python之如何扩展 barh 中 y 刻度的空间之python matplotlib

2025年05月04日14mate10pro

请看附件

我在python中有如下源码

def plotBarChartH(self,data): 
           LogManager.logDebug('Executing Plotter.plotBarChartH') 
 
           if type(data) is not dict: 
               LogManager.logError('Input data parameter is not in right format. Need a dict') 
               return False 
 
           testNames = [] 
           testTimes = [] 
 
           for val in data: 
                testNames.append(val) 
                testTimes.append(data[val]) 
 
           matplotlib.rcParams.update({'font.size': 8})      
           yPos = np.arange(len(testNames)) 
           plt.barh(yPos, testTimes, height=0.4, align='center', alpha=0.4) 
           plt.yticks(yPos, testNames) 
           plt.xlabel('time (seconds)') 
           plt.title('Test Execution Times') 
           savePath = os.path.join(ConfigurationManager.applicationConfig['robotreportspath'],'bar.jpg') 
           plt.savefig(savePath) 
           plt.clf() 
           return True 

酒吧看起来不错,但我有两个问题

  1. y轴的文字如何才能完整显示?我的意思是一些文本被截断了,我想扩展占用空间,以便它可以完整显示。

  2. 我可以增加绘制图表的整个绘图区域吗?我想增加绘图区域的宽度,使图像看起来更大

谢谢

请您参考如下方法:

当您使用 plt.figure(figsize=(width,height)) 创建一个 Figure 对象并调用 时,您可以明确设置图形大小(以英寸为单位) plt.tight_layout()` 为您的刻度标签腾出空间,如下所示:

import matplotlib.pyplot as plt 
 
names = ['Content Channels','Kittens for Xbox Platform','Tigers for PS Platform', 
         'Content Series', 'Wombats for Mobile Platform'] 
 
values = [260, 255, 420, 300, 270] 
 
fig = plt.figure(figsize=(10,4)) 
ax = fig.add_subplot(111) 
yvals = range(len(names)) 
ax.barh(yvals, values, align='center', alpha=0.4) 
plt.yticks(yvals,names) 
plt.tight_layout() 
 
plt.show()