【问题标题】:Sankey diagram matplotlib save scale issue桑基图matplotlib保存比例问题
【发布时间】:2017-05-01 22:02:54
【问题描述】:

使用matplotlib 生成来自维基百科的数据的桑基图(看起来很糟糕的数据,但我想我会找出代码然后去寻找更好的数据)。而且我似乎无法正确缩放文件。

在 macOS 10.12.4 的系统 Python.app 中使用plt.show()显示很好,并且简单的示例保存了 fine,但添加 scale = 0.0001 似乎以某种方式破坏了plt.savefig()。我尝试更改 dpi 参数,但它似乎根本不影响结果。我还尝试将scale 参数添加到savefig,但这似乎根本没有做任何事情(甚至没有破坏它?)。

我可以从Python.app 保存它,它看起来不错,但我真的很想弄清楚出了什么问题。

import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey

fig = plt.figure(figsize = (13, 7), frameon = False)
ax = fig.add_subplot(1, 1, 1, xticks = [], yticks = [], title='Global Electricity Production & Consumption 2005'
                     )
g = [-12192, 6157, 1960, 387, 2383, 1240]              # generated
c = [4250, -7942, -1418, -1266, -1017, -8.79]          # consumed
sankey = Sankey(ax = ax, 
        format = '%.5G', 
        head_angle = 135,  
        unit = ' TWh', 
        gap = 0.3, 
        scale = 0.0001,
        margin = 0.0,
        offset = 0.2,
        shoulder = 0.0)

sankey.add(
    patchlabel = 'Production',
    flows = g,
    orientations = [0, 0, -1, -1, 1, 1], 
    labels = [None, 'Coal', 'Natural Gas', 'Petroleum', 'Nuclear', 'Renewable'],
    pathlengths = [0.0, 0.2, 0.2, 0.6, 0.2, 0.2]
    )

sankey.add(
    flows = [12192, -4250, -7942],
    orientations = [0, 0, -1],
    labels = [None, None, 'Conversion Losses'],
    pathlengths = [-.2, -.2, 0.4],
    # trunklength = 1.0,
    prior = 0,
    connect = (0, 0))       # denotes which flow index from the prior to connect to which flow index in this one

sankey.add(
    patchlabel = 'Gross Generation\n4250 TWh',
    flows = [4250, -1418, -1266, -1017, -8.79, -541],
    orientations = [0, 0, -1, 1, -1, 1],
    labels = [None, 'Residential', 'Commercial', 'Industrial', 'Transportation', '?'],
    prior = 1,
    pathlengths = [0.2, 0.2, 0.2, 0.2, 0.7, 0.2],
    # trunklength = 2.5,
    connect = (1, 0)
)


plt.savefig('./Global_Electrical_Energy_Prod_Cons_2005.png', 
                dpi = 300, 
                frameon = None,
                transparent = True,
                scale = 0.0001)
sankey.finish()
plt.show()

plt.show()发起的Python.app保存的预期结果。

令人费解的结果(编辑:这是打乱的,但这是因为它仍然设置为 300 dpi,使用默认设置让 stackoverflow 正确显示它)。我刚刚尝试了.pdf.svg 并得到了相同的结果。

【问题讨论】:

  • 也许在调用sankey.finish()之后尝试保存?
  • 好主意!我希望我曾想过尝试它,但看起来它也不起作用,同样的结果。
  • 你确定吗?当我运行代码时确实可以解决它...
  • 其实,不,我不确定!我刚刚意识到我在错误的文件中编辑了它(我复制了代码以开始添加新数据,但仍然运行原始文件)我目前无法测试它,因为我的计算机刚刚因内存问题而死机,但我应该可以在一分钟内检查它——听起来很有希望,谢谢!
  • 您确实需要在保存之前完成您的 sankey plot。顺便提一下,savefig 没有 scale 参数,所以最好不要使用它。

标签: python matplotlib scale sankey-diagram


【解决方案1】:

您需要在保存之前完成 sankey 图。更改这些行的顺序:

sankey.finish()
plt.savefig(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 2022-01-17
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多