Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set Xticks according to key from a dictionary

How can the xticks get set from the key in a dictionary? In my original code the dictionary is empty and fills according to a data file so I can't have anything static for the xticks. Depending on what the user inputs (a number from 1-10) the graph plots from highest to lowest values of that amount but I want the user to be able to see what IP the value pertains to. The keys are IP addresses so the ticks will also have to be vertical since they take up a fair amount of space. Thanks

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.") 
like image 970
k5man001 Avatar asked Apr 24 '17 00:04

k5man001


People also ask

How do you check for the existence of a key in a dictionary?

You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key().


1 Answers

There are two steps to correctly setting the labels on the x-axis from your example. You have to get the correct keys from your dictionary, and then you have to set them as the axis labels (and rotate them so that they are legible).

1) Get the the correct labels

The labels are the keys of your dictionary. The problem is that the keys in a dictionary aren't ordered and you need them in the same order as your sorted values.

Getting dictionary keys sorted by the values can be done several ways, but in your code you are already looping over the keys in the correct order in your for loop. Add a new list variable to store the keys like this:

    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())

Now the x_labels list contains the labels you want in the correct order.

2) Set the xtick labels

Setting the labels requires adding a call to ax.set_xticklabels() after setting the x tick positions with ax.set_xticks(). You can also specify the rotation of the labels in the call to ax.set_xticklabels(). The added line is shown here:

    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.

With these lines added to your code, I get the following graph (when I select the top 5 domains): Graph with text labels

like image 62
Craig Avatar answered Sep 29 '22 02:09

Craig