设置matplotlib图中“ylabel”的位置

2024-06-09 14:46:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用matplotlib(source)重新创建下图的外观。

Template figure

但是,我在放置ylabel时遇到问题。我想要它在y轴的顶部,就像它在图上一样。我试过用ax.yaxis.set_label_position()来设置它的位置,但这只接受y轴的leftright。是否有控制ylabel位置的选项,或者我应该使用ax.text并手动设置文本的位置?

编辑:结果是,ax.set_ylabel(position=(x,y))设置标签相对于图形坐标的位置。但是,由于它的水平旋转,标签向右有点太多,并且position(x,y)似乎不接受负输入。有办法把标签向左移一点吗?

我在这里包含了用于生成图形骨架的代码,尽管它相当混乱。

import  matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r"\usepackage[charter]{mathdesign}"]
mpl.rcParams['font.family'] = ['serif']
mpl.rcParams['font.size'] = 10

nb_procs   = np.array([1,     2,        4,      12,     24,    48,     96,     192,    384])

def adjust_spines(ax, spines):
    for loc, spine in ax.spines.items():
        if loc in spines:
            spine.set_position(('outward', 10))  # outward by 10 points
            spine.set_smart_bounds(True)
        else:
            spine.set_color('none')  # don't draw spine

    # turn off ticks where there is no spine
    if 'left' in spines:
        ax.yaxis.set_ticks_position('left')
    else:
        # no yaxis ticks
        ax.yaxis.set_ticks([])

    if 'bottom' in spines:
        ax.xaxis.set_ticks_position('bottom')
    else:
        # no xaxis ticks
        ax.xaxis.set_ticks([])

# -- We create the figure.
figPres = plt.figure(figsize=(3,1.75))
axPres  = figPres.add_subplot(111)

# -- We remove any superfluous decoration.
# Remove the axis decorations on the right and on the top.
axPres.spines['top'].set_visible(False)
axPres.spines['right'].set_visible(False)

# Make the remaining spines a light gray.
axPres.spines['bottom'].set_color('gray')
axPres.spines['left'].set_color('gray')

adjust_spines(axPres, ['left', 'bottom'])

# -- Set the x ticks.
axPres.set_xscale('log')
axPres.set_xlim((0.75,500))
axPres.set_xticks((nb_procs))
axPres.set_xticklabels( (r'1', r'2', r'4', r'12', r'24', r'48', r'96', r'192', r'384'), color='gray' )
axPres.xaxis.set_ticks_position('bottom')

for tic in axPres.xaxis.get_major_ticks():
  tic.tick1On = tic.tick2On = False

# -- Set the y ticks.
axPres.set_ylim((0,1))
axPres.set_yticks((0.0,0.5,1.0))
axPres.set_yticklabels((r'0', '', r'1'))
axPres.yaxis.set_ticks_position('left')
axPres.tick_params(axis='y', colors='gray')

#for tac in axPres.yaxis.get_major_ticks():
#  tac.tick1On = tac.tick2On = False
for toc in axPres.xaxis.get_minor_ticks():
  toc.tick1On = toc.tick2On = False

# -- Set the titles of the axes.
axPres.set_ylabel(r"Efficacit\'e", color='gray', rotation='horizontal')
axPres.yaxis.set_label_position('right')
axPres.set_xlabel(r"Nombre de processeurs", color='gray')

plt.show()

Tags: theinpositionaxleftmplcolorset
1条回答
网友
1楼 · 发布于 2024-06-09 14:46:50

您可以使用^{}移动ylabel,它确实接受负数。在您的示例中,我删除了带有set_label_position的行,并添加:

axPres.yaxis.set_label_coords(-0.1,1.02)

enter image description here

相关问题 更多 >