如何在matplotlib中创建竖直方向的直立文本?

8
在 Matplotlib 中,通过添加 rotation='vertical' 参数可以轻松创建一个垂直旋转 90 度的文本对象,例如:enter image description here。但是我想要创建像这样的文本对象:enter image description here。如何实现呢?

我认为没有这样的方法,因为你想要的是一个分割后的字符串。以下是一种方法:text = '2018-08-11',然后将其拆分为单个字符,如 chars = [j for i in text.split('-') for j in i],然后循环遍历它们并使用 plt.text,其中 x 固定,y 值变化。 - Sheldore
1个回答

18
你可以使用'\n'.join(my_string)将换行符(\n)插入到字符串(my_string)的每个字符之间。
如果你还想去掉-符号(这是你问题中隐含的意思),你可以使用.replace()函数将它们去掉。
考虑以下例子:
import matplotlib.pyplot as plt

my_string = '2018-08-11'

fig, ax = plt.subplots(1)

ax.text(0.1, 0.5, my_string, va='center')
ax.text(0.3, 0.5, my_string, rotation=90, va='center')
ax.text(0.5, 0.5, '\n'.join(my_string), va='center')
ax.text(0.7, 0.5, '\n'.join(my_string.replace('-', '')), va='center')

plt.show()

输入图像描述


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