在matplotlib中连接两个Sankey图

时间:2013-12-06 13:27:30

标签: python matplotlib sankey-diagram

我正在尝试使用matplotlib代表一个国家的天然气平衡。

我的想法是,有三种进口天然气来源,我想使用一个Sankey进行绘制,并将其连接到另一个Sankey,其中包含其他气体来源(生产,储气)和天然气消费者作为流出物。

我尝试了很多次但我无法将两张图连在一起

每个图表分别按设计绘制。但是,只要我添加"prior=0, connect=(3,0)",这可能会将两个图连接在一起,一切都会出错,给我一些我无法完全理解的错误。这是代码。

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


ImportLabels=["Imports by\nNaftogaz","Imports by\nOstchem","Imports from\nEurope", ""]
ImportFlows=[11.493,9.768,1.935,-23.196]
ImportOrientation=[0,1,-1,0]

l=["Imports","Private\nextraction","State\nextraction","Net supplies\ntoUGS","Households","TKE","Metallurgy","Energy","Other\nIndustries","Technological\nlosses"]
v=[23.196,3.968,13.998,-2.252,-13.289,-7.163,-3.487,-4.72,-7.037,-3.17]
d=[0,-1,1,-1,0,0,1,1,1,-1]

sankey=Sankey(scale=1.0/69,patchlabel="Gas balance",format='%.1f',margin=0.15)
sankey.add(flows=ImportFlows, labels=ImportLabels, orientations=ImportOrientation, label='Imports',fc='#00AF00')
sankey.add(flows=v,labels=l,orientations=d, prior=0, connect=(3,0),label='Second',fc='#008000')

这个想法是连接第一个图表(具有-23.196值)的3个流出量和第二个sankey的流入量(也有23.196个)

这是错误文本:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-1220fede42ce> in <module>()
     14 sankey=Sankey(scale=1.0/69,patchlabel="Gas balance",format='%.1f',margin=0.15)
     15 sankey.add(flows=ImportFlows, labels=ImportLabels,  orientations=ImportOrientation, label='Imports',fc='#00AF00')
---> 16 sankey.add(flows=v,labels=l,orientations=d, prior=0, connect=(3,0),label='Second',fc='#008000')

C:\Python27\lib\site-packages\matplotlib\sankey.pyc in add(self, patchlabel, flows, orientations, labels, trunklength, pathlengths, prior, connect, rotation, **kwargs)
    369                    ("The connection index to the source diagram is %d, but "
    370                     "that diagram has only %d flows.\nThe index is zero-based."
--> 371                     % connect[0], len(self.diagrams[prior].flows))
    372             assert connect[1] < n, ("The connection index to this diagram is "
    373                                     "%d, but this diagram has only %d flows.\n"

TypeError: not enough arguments for format string

所以我不确定两个图之间的连接是否存在问题(sankey.pyc试图显示的文本建议)或matplotlib本身是否有问题,因为"TypeError: not enough arguments for format string"表示?

1 个答案:

答案 0 :(得分:2)

您的问题是您正在进行两次.add()来电。第一次调用Sankey()已经构建了一个图表(默认灰色,1个流入和1个流出)。因此,当您尝试连接到第一个图时,它会失败,因为它只有一个流,并且您尝试连接到第三个流。 (无论如何都会失败,因为流量不匹配。)

您需要在第一个呼叫中设置第一个图表,并且只有一个添加呼叫,例如:

sankey = Sankey(scale=1.0/69,patchlabel="Gas balance",format='%.1f',margin=0.15,
                flows=ImportFlows, labels=ImportLabels, 
                orientations=ImportOrientation, label='Imports',fc='#00AF00')
sankey.add(flows=v,labels=l,orientations=d, label='Second',fc='#008000', prior=0,
           connect=(3, 0))

这给了我: enter image description here