如何根据字典中的键设置 Xticks

k5m*_*001 5 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.") 
Run Code Online (Sandbox Code Playgroud)

Cra*_*aig 8

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

1) 获取正确的标签

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

可以通过多种方式获取按值排序的字典键,但在您的代码中,您已经在循环中以正确的顺序遍历键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())
Run Code Online (Sandbox Code Playgroud)

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

2)设置xtick标签

设置标签需要ax.set_xticklabels()在使用ax.set_xticks(). 您还可以在对 的调用中指定标签的旋转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.
Run Code Online (Sandbox Code Playgroud)

将这些行添加到您的代码中后,我会得到下图(当我选择前 5 个域时): 带有文本标签的图表