繁体   English   中英

从字典中绘制数字总和的图表

[英]Draw chart of sum combinations of numbers from a dictionary

给定如下字典,

dict1 = {l: 12, b: 20, k:1, a:10, d:30 }

想要绘制的图表表示字典中数字的每个可能组合的总和。 一种可能组合的图表表示如下。

在此处输入图片说明

组合按总和的降序排列。 在组合中,元素以值的降序显示。

我需要一些具有matplotlibseaborn或类似库的Jupyter笔记本中的帮助。

不知道我是否抓住了所有的可能,但是这是我的最新尝试,该尝试收集了所有可能的组合。 如果要在标签之间figsize出更大的空白,则需要增大figsize或减小fontsize (或确定何时以及如何“破坏”沿x的连续“数字线”)。

结果:

matplotlib中类似流程图的数字行

码:

import itertools
import matplotlib.pyplot as plt
import matplotlib as mpl

input_dict= {'l': 12, 'b': 20, 'k':1, 'a':10, 'd':30 }

combinations=[]
## set the length of calculated combinations here:
for lengths in range(1,len(input_dict)):
    perm_length=lengths
    combinations += list(map( dict, itertools.combinations( input_dict.items(), perm_length  ) )  )

sum_dict={}
for d in combinations:
    s=sorted(d,key=d.get,reverse=True)
    sum_dict[sum(d.values())]=list(s)
ordered_dict={x:sum_dict[x] for x in sorted(sum_dict, reverse=True )}

## plotting
fig,ax=plt.subplots(figsize=(10,5))
arrow_props = dict(fc='k', ec='k', 
                    headlength=10, headwidth=3, 
                    width=.5,shrink=0.15,zorder=2)

## make some nice colors:
cmap = mpl.cm.get_cmap('nipy_spectral')
norm=mpl.colors.Normalize(vmin=0,vmax=len(ordered_dict))


for i,a_sum in enumerate(ordered_dict.items()):
    ### iterate over the "addends", plot them at y=1:
    for ie,elem in enumerate(a_sum[1]):
        perm_length=len(a_sum[1])

        _txt='{0} ({1})'.format( elem, input_dict[elem])

        ## I create a ax.text() and ax.annotate() separately, 
        #  in order to have more granular control of the appearance
        _offset=-(perm_length-1)/(2*perm_length)
        ax.text(i + ie/perm_length +_offset , 1 , _txt, 
                ha="center",va="bottom",rotation=90, fontsize=8,
                bbox=dict(facecolor=cmap(norm(i)), alpha=0.5))

        ax.annotate("", xy=(i,0), xytext=(i + ie/perm_length +_offset, 1 ), 
                    ha='center',arrowprops=arrow_props)

    ## plot the sum at y=0    
    ax.text(i,0,a_sum[0],
            ha="center",va="center",rotation=90, fontsize=8,
            bbox=dict(facecolor=cmap(norm(i)), alpha=0.5))

ax.set_xlim(-1,len(ordered_dict)+1)
ax.set_ylim(-1,2)

plt.tight_layout()
plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM