如何根据字典

时间:2017-04-24 00:34:08

标签: python dictionary matplotlib

如何从字典中的键设置xticks?在我的原始代码中,字典是空的,并根据数据文件填充,因此我不能为xticks提供任何静态内容。根据用户输入的内容(1-10中的数字),图表从该值的最高值到最低值进行绘制,但我希望用户能够看到该值与哪些IP相关。密钥是IP地址,因此它们也必须是垂直的,因为它们占用了相当大的空间。感谢

from collections import Counter
import matplotlib.pyplot as plt
import numpy as np


frequency2 = Counter({'205.166.231.2': 10, '205.166.231.250': 7, '205.166.231.4': 4, '98.23.108.3': 2, '205.166.231.36': 1})


vals = sorted(frequency2.values(), reverse=True)
response2 = int(input("How many top domains from source? Enter a number between 1-10: "))

if response2 > 0 and response2 < len(vals)+1:

    figure(1)    

    y = vals[:response2]

    print ("\nTop %i most domains are:" %response2)
    for key, frequency2_value in frequency2.most_common(response2):
        print("\nDomain IP:",key,"with frequency:",frequency2_value)        

    x = np.arange(1,len(y)+1,1)

    fig, ax = plt.subplots()

    ax.bar(x,y,align='center', width=0.2, color = 'g')    
    ax.set_xticks(x)
    ax.set_xlabel("This graph shows amount of protocols used")
    ax.set_ylabel("Number of times used")
    ax.grid('on')

else:
    print ("\nThere are not enough domains for this top amount.") 

1 个答案:

答案 0 :(得分:3)

从示例中正确设置x轴上的标签有两个步骤。您必须从字典中获取正确的密钥,然后必须将它们设置为轴标签(并旋转它们以使其清晰易读)。

1)获取正确的标签

标签是您字典的键。问题是字典中的键没有排序,您需要它们的顺序与排序值相同。

获取dictionary keys sorted by the values可以通过多种方式完成,但在您的代码中,您已经在for循环中以正确的顺序循环键。添加一个新的列表变量来存储这些键:

    x_labels = [] #create an empty list to store the labels
    for key, frequency2_value in frequency2.most_common(response2):
        print("\nDomain IP:",key,"with frequency:",frequency2_value)        
        x_labels.append(key) #store each label in the correct order (from .most_common())

现在x_labels列表按正确的顺序包含您想要的标签。

2)设置xtick标签

设置标签需要在使用ax.set_xticks()设置x刻度位置后添加对ax.set_xticklabels()的调用。您还可以在调用ax.set_xticklabels()时指定标签的旋转。添加的行显示在此处:

    ax.bar(x, y, align='center', width=0.2, color = 'g')
    ax.set_xticks(x)    
    ax.set_xticklabels(x_labels, rotation=90) #set the labels and rotate them 90 deg.

将这些行添加到您的代码中,我得到以下图表(当我选择前5个域时): Graph with text labels