Python中的字符串连接" r" matplotlib中的前缀和换行符

时间:2017-03-19 10:55:11

标签: python matplotlib text latex concatenation

我想在matplotlib轴上写一些文字。此文本包含换行符,LaTex文本呈现应该可以访问。

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as mpl

mpl.rc('font', family='sans-serif')
mpl.rc('text', usetex=True)

fig = mpl.figure()
ax = fig.add_subplot(1,1,1)

text = (r"This is the first line"
         "\n"
         r"And here comes the second one")

ax.text(0.2,0.5,text)

产生以下输出:

enter image description here

现在我想把这两个句子连在一起,这样我就整篇文章的不同输入都很灵活。我在考虑像

这样的事情
text_1 = "This is the first line"
text_2 = "And here comes the second one"

completeText = [text_1, text_2]

textIn = '⧹n'.join(map(str, completeText))

ax.text(0.2,0.5,textIn)

然而,这会产生错误

UnicodeEncodeError: 'ascii' codec can't encode character '\u29f9' in position 300: ordinal not in range(128)

此外,是否可以在每个新行的前面放置一个像LaTex itemize一样的项目符号?

1 个答案:

答案 0 :(得分:2)

检查您的'\n',确保它不是'⧹n'

我使用'\n'替换代码中的'⧹n'。代码已成功运行。

区别在于\

关于子弹,试试这个,它可以在我的ipython笔记本上运行。

%matplotlib inline    # this line is for my ipython notebook,you don't need it

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as mpl

mpl.rc('font', family='sans-serif')
mpl.rc('text', usetex=True)

fig = mpl.figure()
ax = fig.add_subplot(1,1,1)

text_1 = r"{\bullet}This is the first line"
text_2 = r"{\bullet}And here comes the second one"

completeText = [text_1, text_2]

textIn = '\n'.join(map(str, completeText))

ax.text(0.2,0.5,textIn)


fig.show()