如何在Python Matplotlib中扩展水平条形图的Y轴刻度空间

3
请查看附图。

enter image description here

我有以下的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. 我能增加整个绘图区域吗?我想增加绘图区域的宽度,使图像看起来更大一些。
谢谢。”
4个回答

5

当您使用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()

enter image description here


你正在使用的那个可爱的调色板是什么? - mel
@mel 我认为这只是带有一些透明度的(旧)默认 Matplotlib 蓝色。 - xnx

2
  1. 一种选项是在字符串中包含换行符\n(或者像this答案中使用"\n".join(wrap(longstring,60)之类的东西)。您可以使用fig.subplots_adjust(left=0.3)调整绘图区域,以确保整个字符串被显示。

示例:

import matplotlib.pyplot as plt
import numpy as np

val = 1000*np.random.rand(5)    # the bar lengths
pos = np.arange(5)+.5    # the bar centers on the y axis
name = ['name','really long name here', 
        'name 2', 
        'test', 
        'another really long \n name here too']

fig, ax = plt.subplots(1,1)
ax.barh(pos, val, align='center')
plt.yticks(pos, name)
fig.subplots_adjust(left=0.3)
plt.show()

这提供了

enter image description here

你可以使用figsize参数来调整子图或图表的物理尺寸。

示例:

fig, ax = plt.subplots(1,1, figsize=(12,8))

图形中的空间量可以通过根据数据设置轴来进行调整。
ax.set_xlim((0,800))

或者使用ax.set_xlim((0,data.max()+200))进行自动化。


2
截至2020年,只需在plt上简单调用.autoscale即可:在plt.show()之前进行操作。
plt.autoscale()

或者

plt.autoscale(enable=True, axis='y', tight=None)

1
  1. 如何显示y轴上的完整文本?我的意思是有些文本被截断了,我想扩大它占用的空间,以便完整显示。

您可以使用 plt.axes 控制坐标轴的位置,从而在左侧区域留下更多的空间。例如:plt.axes([0.2,0.1,0.9,0.9])

  1. 我能增加绘图区域的整个面积吗?我想增加绘图区域的宽度,使图像看起来更大一些。

我不明白您的意思。

  • 您可以使用 plt.figure 控制图形的大小(例如:plt.figure(figsize = (6,12)))。
  • 您可以使用 plt.[xy]lim 控制信息与轴之间的空格。例如,如果您想在右侧区域留更多的空白,可以使用 plt.xlim(200, 600)
  • 您可以使用 plt.axes 省略一些边距空间(请参见上述问题1)。

嗨,数组[0.2, 0.1, 0.9, 0.9]代表什么?我在尝试不同的值,但是无法理解它们实际上代表什么。 - slysid
它表示xmin、ymin、xmax和ymax的归一化值。因此,如果您使用0,0,1,1,则没有边距;如果您使用0.1,0.1,0.9,0.9,则在轴和图形边界之间每个侧面留下10%的空白... - kikocorreoso

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接