Python display specific values on x-axis using matplotlib
Question: I'm querying data from a simple sqlite3 DB which is pulling a list of the
number of connections per port observed on my system. I'm trying to graph this
into a simple bar-chart using matplotlib.

Thus far, I'm using the follow code:

    
    
    import matplotlib as mpl
    mpl.use('Agg') # force no x11
    import matplotlib.pyplot as plt
    import sqlite3
    
    con = sqlite3.connect('test.db')
    cur = con.cursor()
    cur.execute('''
            SELECT dst_port, count(dst_port) as count from logs
            where dst_port != 0
            group by dst_port
            order by count desc;
        '''
    )
    
    data = cur.fetchall()
    dst_ports, dst_port_count = zip(*data)
    
    #dst_ports = [22, 53223, 40959, 80, 3389, 23, 443, 35829, 8080, 4899, 21320, 445, 3128, 44783, 4491, 9981, 8001, 21, 1080, 8081, 3306, 8002, 8090]
    #dst_port_count = [5005, 145, 117, 41, 34, 21, 17, 16, 15, 11, 11, 8, 8, 8, 6, 6, 4, 3, 3, 3, 1, 1, 1]
    
    print dst_ports
    print dst_port_count
    
    fig = plt.figure()
    
    # aesthetics and data
    plt.grid()
    plt.bar(dst_ports, dst_port_count, align='center')
    #plt.xticks(dst_ports)
    
    # labels
    plt.title('Number of connections to port')
    plt.xlabel('Destination Port')
    plt.ylabel('Connection Attempts')
    
    # save figure
    fig.savefig('temp.png')
    

When I run the above, the data is successful retrieved from the DB and a graph
is generated. However, the graph isn't what I was expecting. For example, on
the x-axis, it plots all values between 0 and 5005. I'm looking for it to
display only the values in dst_ports. I've tried using xticks but this doesn't
work either.

I've included some sample data in the above code which I've commented out that
may be useful.

In addition, here is an example of the graph output from the above code:

![graph without xticks](http://i.stack.imgur.com/dyhvq.png)

And also a grpah when using xticks:

![graph using xticks](http://i.stack.imgur.com/KXA9C.png)


Answer: You need to create some xdata by `np.arange()`:

    
    
    import matplotlib as mpl
    import numpy as np
    import matplotlib.pyplot as plt
    
    dst_ports = [22, 53223, 40959, 80, 3389, 23, 443, 35829, 8080, 4899, 21320, 445, 3128, 44783, 4491, 9981, 8001, 21, 1080, 8081, 3306, 8002, 8090]
    dst_port_count = [5005, 145, 117, 41, 34, 21, 17, 16, 15, 11, 11, 8, 8, 8, 6, 6, 4, 3, 3, 3, 1, 1, 1]
    
    fig = plt.figure(figsize=(12, 4))
    
    # aesthetics and data
    plt.grid()
    x = np.arange(1, len(dst_ports)+1)
    plt.bar(x, dst_port_count, align='center')
    plt.xticks(x, dst_ports, rotation=45)
    
    # labels
    plt.title('Number of connections to port')
    plt.xlabel('Destination Port')
    plt.ylabel('Connection Attempts')
    

Here is the output:

![enter image description here](http://i.stack.imgur.com/DsVSS.png)

