使用 matplotlib 在 x 轴下方等距离对齐多个标签

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

我正在尝试使用 matplotlib 在 x 轴下方添加一些标签。我有 5-6 个标签,我想将它们绘制在 x 轴下方。这些标签的文本会有所不同,因此不可能使用单一设置来呈现标签。我在下面给出了一个最小的例子。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Generate sample data

frame_width = 1920
frame_height =1080 

##plotting function begins
fig, ax = plt.subplots(1,1,figsize=(frame_width/100,frame_height/100))

ax = plt.gca()
fig = plt.gcf()
fig_width = fig.get_figwidth() * fig.dpi

txtcolor='White'
text_font_size=12
textfont='Arial'

# Show only the x-axis
ax.set_xlim(1, 20)

txt1="ATTENTION"
a1 = plt.figtext(0.15, 0.070, txt1, ha='left',va='center',weight='bold',c=txtcolor,family=textfont ,fontsize=text_font_size, bbox=dict(facecolor='g', edgecolor='g'))
txt1_width = a1.get_window_extent().width / fig_width
txt2_x = txt1_width + 0.15 + 0.02 

txt2="CONVICTION"
a2=plt.figtext(txt2_x, 0.070, txt2, ha='left',va='center',weight='bold',c=txtcolor,family=textfont ,fontsize=text_font_size, bbox=dict(facecolor='c', edgecolor='c'))
txt2_width = a2.get_window_extent().width / fig_width
txt3_x = txt2_width + 0.15 + 0.03 + txt1_width

txt3="INTEREST IN SPORTS"
a3=plt.figtext(txt3_x, 0.070, txt3, ha='left',va='center',weight='bold',c=txtcolor,family=textfont ,fontsize=text_font_size, bbox=dict(facecolor='m', edgecolor='m'))
txt3_width = a3.get_window_extent().width / fig_width
txt4_x = txt2_width + 0.15 + 0.03 + txt1_width + txt3_width

plt.show()

我试图获取文本的宽度+添加填充,以便下一个文本不会重叠。但是,由于文本长度不同,我必须更改设置以避免重叠或在文本标签之间产生更大的间隙。如何动态渲染它,以便文本标签看起来均匀间隔,无论文本大小如何。

python matplotlib
1个回答
0
投票

如果您使用

annotate
,您可以放置与任何其他艺术家相关的文本,包括另一个注释。在这里,我相对于轴放置第一个文本。通过将文本 1.5 字体大小 (
xytext=(1.5, 0)
) 放置在前一个注释 (
xy=(1, 0)
) 右侧的右侧来放置后续注释。

import matplotlib.pyplot as plt

# Generate sample data

frame_width = 1920
frame_height =1080 

##plotting function begins
fig, ax = plt.subplots(1,1,figsize=(frame_width/100,frame_height/100))

ax = plt.gca()
fig = plt.gcf()
fig_width = fig.get_figwidth() * fig.dpi

txtcolor='White'
text_font_size=12
textfont='Arial'

# Show only the x-axis
ax.set_xlim(1, 20)

txt1="ATTENTION"
ann = ax.annotate(txt1, (0, -0.1), ha='left',va='center',weight='bold',
                  c=txtcolor, family=textfont, fontsize=text_font_size,
                  xycoords='axes fraction',
                  bbox=dict(facecolor='g', edgecolor='g'))

for txt, color in zip(["CONVICTION", "INTEREST IN SPORTS"], ['c', 'm']):
    ann = ax.annotate(txt, (1, 0.5), xycoords=ann, xytext=(1.5, 0), 
                      textcoords='offset fontsize', va='center', weight='bold',
                      c=txtcolor, family=textfont, fontsize=text_font_size,
                      bbox=dict(facecolor=color, edgecolor=color))

plt.show()

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