Tik*_*ik0 6 python plot numpy matplotlib
以下python3代码不起作用,因为第9行中的双线换行:
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import numpy as np
plt.xkcd()
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.text(4, 400, '-> 1 Pig ~ 150 kg\n\n-> Butching => 80 to 100 kg meat')
plt.axis([0, 7, 0, 2000])
plt.plot([0,1,2,3,4,5], [0,400,800,1200,1600, 2000])
ax.set_ylim([0, 2000])
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.show()
Run Code Online (Sandbox Code Playgroud)
但是,如果我删除该plt.xkcd()行,那么即使使用双线换行,一切也能正常工作.现在有人为什么?这是一个错误还是有任何解决方法?
我的设置: Windows 7 amd64,python 3.3,numpy 1.8,matplotlib 1.3.1
解决这个问题的两个技巧:
将双换行符替换为“\n.\n”(即添加一个小点)
plt.text(4, 400, '-> 1 Pig ~ 150 kg\n.\n-> Butching => 80 to 100 kg meat')
Run Code Online (Sandbox Code Playgroud)将多行文本拆分为多个文本调用(最佳结果)
plt.text(4, 400, '-> 1 Pig ~ 150 kg')
plt.text(4, 240, '-> Butching => 80 to 100 kg meat')
Run Code Online (Sandbox Code Playgroud)
或者
text = '-> 1 Pig ~ 150 kg\n\n-> Butching => 80 to 100 kg meat'
for il, l in enumerate(text.split('\n')):
plt.text(4, 400-80*il, l)
Run Code Online (Sandbox Code Playgroud)