2013-12-17 26 views
6

以下python3代碼不會在9號線工作,因爲斷行的,:雙斷行失敗,matplotlib和XKCD風格

# -*- 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() 

但如果我刪除plt.xkcd()線,然後一切工作正常,即使與雙重線決裂。 現在有人爲什麼? 這是一個錯誤還是有任何解決方法?

我的設置: Windows 7的AMD64, 蟒蛇3.3, numpy的1.8, matplotlib 1.3.1

+0

和它與plt.xkcd線工作,如果去掉雙斷行?你確定這是因爲雙重換行嗎?因爲我的matplotlib版本太低n的錯誤重現在plt.xkcd()提供錯誤 - – usethedeathstar

+0

@mutzmatron我修正了他的代碼,錯誤報告正確...我在這裏轉載 –

+0

我打開了這個問題在matplotlib的問題跟蹤器在GitHub上...](https://github.com/matplotlib/matplotlib/issues/2687) –

回答

1

兩個黑客來解決這個問題:

  • 與更換雙新行「 \ n「(即加一個小點)

    plt.text(4, 400, '-> 1 Pig ~ 150 kg\n.\n-> Butching => 80 to 100 kg meat') 
    
  • 分裂您的多行文本到多次調用文字(最好的結果)

    plt.text(4, 400, '-> 1 Pig ~ 150 kg') 
    plt.text(4, 240, '-> Butching => 80 to 100 kg meat') 
    

    或者

    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) 
    
+0

你的第一個例子不好,因爲點。即使這些\ n之間的安全空白(\ xA0)也不會工作。其他兩個都很好,但不會隨着我的文本大小而擴展,所以它不是最終的解決方案。 – Tik0

+0

同意 - 對於更完整的修復,您可以添加textsize參數並使用它來縮放間距(而不是我使用的任意值80)。再次,這些主要是針對特定問題的解決方法,而不是值得添加到matplotlib代碼庫中的錯誤修正:) – jmetz

+0

如果只在'\ n'之間放置空格,會發生什麼情況? – tacaswell