如何在Matplotlib标签中更改文本对齐方式?

3
我用Matplotlib制作了一个图表,想要改变旋转的y轴标签的对齐方式。在这个代码示例中,“This is an example plot”文本应该向左对齐。将原始答案翻译成“最初的回答”。
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
axes.plot([0, 1], [0, 1])
axes.set_ylabel('This is an\nexample plot', rotation=0)
axes.yaxis.set_label_coords(0.1, 0.9)
plt.show()

plot figure with a label with centered text

2个回答

4

Matplotlib的文本命令,例如标签和注释,支持许多关键字参数,这些参数可以影响对齐、方向、间距、字体等。在文档中可以找到完整的文本属性列表。在上面的例子中。

axes.set_ylabel('This is an\nexample plot', rotation=0, horizontalalignment='left')

能做到这一点的方法是使用以下代码:

如其他答案中所述,此特定示例滥用了y轴标签。但所有种类的Matplotlib标签的基本原则都是相同的。


0
我不会以这种方式操作ylabel。相反,只需在您想要的位置放置一些文本即可。
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
    
figure, axes = plt.subplots()
axes.plot([0, 1], [0, 1])
    
axes.add_artist(AnchoredText('This is an\nexample plot', "upper left", frameon=False))
    
plt.show()

plot with text anchored in top left corner


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