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

标签 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.") 

最佳答案

根据您的示例正确设置 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_xticklabels()使用 ax.set_xticks() 设置 x 刻度位置后。您还可以在调用 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

关于python - 如何根据字典中的键设置 Xticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43578055/

相关文章:

python - Django 属性错误 : 'str' object has no attribute 'tzinfo'

c# - 如何引用引用类型字典键的属性?

python - 使用 matplotlib 对 3d 图进行标签操作

python - Matplotlib 强制虚线接触轴

python - "Replot"IPython 笔记本中的 matplotlib 内联图

python - 级数计算精度

python - 使用另一个数组搜索一个数组

python - 如何在 Python 中将函数写入打开的文件?

c# - 在 C# 中连接两个具有不同数据类型的字典

java - 重构建议: maps to POJOs