【问题标题】:Double linebreak fails with matplotlib and xkcd style双换行失败,matplotlib 和 xkcd 风格
【发布时间】:2014-01-05 09:33:49
【问题描述】:

以下 python3 代码不起作用,因为第 9 行中的 double 换行符:

# -*- 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() 行,那么即使使用双换行符,一切正常。 现在有人为什么吗? 这是一个错误还是有任何解决方法?

我的设置: 视窗 7 amd64, 蟒蛇3.3, 麻木1.8, matplotlib 1.3.1

【问题讨论】:

  • 如果删除双换行符,它是否适用于 plt.xkcd 行?你确定是因为双换行吗? - 无法重现,因为我的 matplotlib 版本太低 n 在 plt.xkcd() 处出错-
  • @mutzmatron 我修复了他的代码并正确报告了错误...我在这里转载
  • xkcdmatplotlib 自 1.3 版以来的标准组件。我还可以重现错误(删除双换行符或plt.xkcd())。

标签: python numpy matplotlib plot


【解决方案1】:

解决此问题的两个技巧:

  • 将双换行符替换为“\n.\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)
    

【讨论】:

  • 你的第一个例子很糟糕,因为点。即使是那些 \n 之间的安全空白 (\xA0) 也不起作用。其他两个都不错,但不适合我的textsize,所以不是终极解决方案。
  • 同意 - 要获得更完整的修复,您可以添加 textsize 参数并使用它来缩放间距(而不是我使用的任意值 80)。同样,这些主要是针对特定问题的解决方法,而不是值得添加到 matplotlib 代码库的错误修复:)
  • 如果你在\n之间放一个空格会发生什么?
  • @tcaswell:试过了,不行——最后一行没有显示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 2016-06-21
相关资源
最近更新 更多