在绘图中调整右侧文本

问题描述 投票:0回答:1

我想在每个堆积条的右侧打印一些文本。我已经找到了一种通过注释来实现的方法,但是存在一些问题:autolabel函数在我看来是一种非常多余的注释方法,是否有更简单的方法来实现相同的视觉效果,更容易吗?更重要的是,我如何才能解决此文本超出图右侧的问题,如下所示?我已经尝试过subplots_adjust,但是并没有完全起作用...

enter image description here

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the x-axis label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()#(figsize=(6, 4), dpi=200)
# FOR SIDE-BY-SIDE plotting:
# rects1 = ax.bar(x - width/2, men_means, width, label='Men')
# rects2 = ax.bar(x + width/2, women_means, width, label='Women')
rects1 = ax.bar(x, men_means, width, label='Men')
rects2 = ax.bar(x, women_means, width, bottom=men_means, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + 3 * rect.get_width() / 2, rect.get_y() + height / 2),
                    xytext=(0, -5),
                    textcoords="offset points",
                    ha='center', va='center')

autolabel(rects1)
autolabel(rects2)
fig.subplots_adjust(left=0.9, right=1.9, top=0.9, bottom=0.1)
plt.show()
python matplotlib bar-chart figure
1个回答
0
投票

如果您不介意最右边的条距刻度标签略微偏离中心,则可以将其稍微向左移动,以使标签适合。

[如果您打印通过调用bar()返回的内容,您会看到它是具有5个艺术家的BarContainer对象:

<BarContainer object of 5 artists>

...,您可以对其进行迭代:

Rectangle(xy=(-0.175, 0), width=0.35, height=20, angle=0)
Rectangle(xy=(0.825, 0), width=0.35, height=34, angle=0)
Rectangle(xy=(1.825, 0), width=0.35, height=30, angle=0)
Rectangle(xy=(2.825, 0), width=0.35, height=35, angle=0)
Rectangle(xy=(3.825, 0), width=0.35, height=27, angle=0)

每个Rectangle对象都有一个set_xy()方法。因此,您可以按照以下方式移动最终的上下栏:

bar, bar2 = rects1[4], rects2[4]
bar.set_xy((bar.get_x()-0.05,bar.get_y()))
bar2.set_xy((bar2.get_x()-0.05,bar2.get_y()))

通过将上面的代码放在您的下面

rects1 = ax.bar(x, men_means, width, label='Men')
rects2 = ax.bar(x, women_means, width, bottom=men_means, label='Women')

并且通过删除对subplots_adjust()的呼叫,改为使用tight_layout(),我能够实现这一目标:

first_option

或者,如果您不介意标签和条形图之间的间距缩小,则可以在rect.get_x() + 3函数中将rect.get_x() + 2.5更改为autolabel(),以达到以下目的:second_option

© www.soinside.com 2019 - 2024. All rights reserved.