Skip to main content
 首页 » 编程设计

python之在 matplotlib 字幕中偏移一个字符

2025年05月04日10luoye11

friend ,

我有一个带有 70 个刻度的绘图轴,代表一个蛋白质序列。由于我无法在一行中放那么多字母并使它们清晰可辨,因此我必须错开它们,因此:

________________________________ 
P o A i I A o g e u n e f e t r 
 l t x s s L n S q e c O L t e s 

(实际图形中字母之间的间距要小得多,如果在一行上,它们会完全重叠。)

我想用星号或其他东西强调其中的某些:

________________________________ 
P o A i I A o g e u n e f e t r 
 l t x s s L n S q e c O L t e s 
*   *   * **   *       * * 

但是当我使用简单的换行符在 Matplotlib 中渲染它时,星号比它们需要的要低得多:

xLabels = [ 
        ['', '\n'][i%2] 
        +sequence[i]  
        +['\n', ''][i%2]  
        +'\n'  
        +decorations[i]   
    for i in range(len(sequence))] 

我知道 matplotlib 在其标签中支持 TeX,我知道我可以在 LaTex 中使用\vspace{-1em} 或其他东西,但我就是无法让 matplotlib 服从我。它不断抛出解析错误,就像这样:

File "/usr/lib64/python3.3/site-packages/matplotlib/mathtext.py", line 2345, in parse 
  str(err)])) 
ValueError:  
$ $ 
^ 
Expected end of text (at char 0), (line:1, col:1) 

(这是我尝试将装饰置于 TeX 数学模式,希望添加上标。可能的复杂情况是许多装饰是 ' '。)

所以,有了这个,我的问题是:有没有办法告诉 matplotlib 的文本渲染器将字符向上移动换行符的一小部分?这需要易于自动化,因为整个程序将生成近四十个数字,每个数字可能都有不同的装饰。

请您参考如下方法:

...is there a way to tell matplotlib's text renderer to move a character up a fraction of a newline?

我认为您走在正确的轨道上。您可以通过您提到的以下 Latex 命令更改 matplotlib 中的垂直间距;但是,我认为您将希望使用 xticks 与 xlabel 来满足您的多行条件。另外,请记住 tex 中的换行符是 \\,而不是 \n。

import numpy as np 
x = np.arange(0, 5, 0.1); 
y = np.sin(x) 
plt.plot(x, y) 
plt.ylim(plt.ylim()[::-1]) 
plt.xlabel(r"first line \\ \vspace{0.5cm}small space \\ \vspace{2cm}{more space}",fontsize=22) 
plt.show()  

另请参阅 Text rendering With LaTeX