当值表示数字和颜色时,绘制字典值

时间:2017-09-27 09:38:04

标签: python dictionary matplotlib

字典显示了多少块水果和椭圆应该是什么颜色。 我正在查看示例代码,如下所示绘制字典

例如: my_dict {' apples':[20,'#2E9127'],' pears':[3,'#FB9A27'],&# 39;樱桃':[7,'#187429']}

所以这样情节将显示该颜色#20E9127的20个点。

此时

键不相关,但value1是计数,v2是十六进制颜色 所以当我制作elipse(graph below or click this link)时,我希望看到20次#2E9127,3次#FB9A27和7次#187429。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse

    NUM = len(my_dict) #but dont want total random dots so thinking this is 
                          #sum of value 1 possibly in a loop


     #example from matplotlib
     # so clearly dont want random np values
    ells = [Ellipse(xy=np.random.rand(2) * 10,
                    width=np.random.rand(), height=np.random.rand(),
                    angle=np.random.rand() * 360)
            for i in range(NUM)]

    #ME HAVING A CRACK!
    # 
    ells = [Ellipse(xy=my_dict(2) * 10,
                    width=np.random.rand(), height=np.random.rand(),
                    angle=np.random.rand() * 360,facecolor=y)
            for i in range(NUM)]


    fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
    for e in ells:
        ax.add_artist(e)
        e.set_clip_box(ax.bbox)
        e.set_alpha(np.random.rand())
        e.set_facecolor(np.random.rand(3))

    ax.set_xlim(0, 10)
    ax.set_ylim(0, 10)

    plt.show()

enter image description here

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,你想要绘制尽可能多的椭圆,就像字典中给出的值的总和一样。 (20个苹果,7个樱桃,3个梨)

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse

my_dict ={'apples': [20, '#2E9127'], 'pears': [3, '#FB9A27'], 'cherries': [7, 'crimson']}

fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})

for key, val in my_dict.items():
    color = val[1]
    for i in range(val[0]):
        el = Ellipse(xy=np.random.rand(2) * 10,
                    width=np.random.rand(), height=np.random.rand(),
                    angle=np.random.rand() * 360, color=color)
        ax.add_artist(el)


ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

plt.show()

我让樱桃红了,能够清楚地看到它们:

enter image description here