Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double linebreak fails with matplotlib and xkcd style

The following python3 code does not work, because of the double linebreak in line 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()

But if I remove the plt.xkcd() line, then everything works fine even with the double linebreak. Does anyone now why? Is it a bug or is there any workaround?

My Setup: Windows 7 amd64, python 3.3, numpy 1.8, matplotlib 1.3.1

like image 753
Tik0 Avatar asked Dec 17 '13 14:12

Tik0


1 Answers

Two hacks to fix this:

  • replace the double newline with "\n.\n" (i.e. add a small dot)

    plt.text(4, 400, '-> 1 Pig ~ 150 kg\n.\n-> Butching => 80 to 100 kg meat')
    
  • Split your multiline text into multiple calls to text (best result)

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

    Or

    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)
    
like image 198
jmetz Avatar answered Oct 19 '22 04:10

jmetz