Python使用matplotlib在x轴上显示特定值

时间:2014-07-10 10:55:53

标签: python graph matplotlib

我从一个简单的sqlite3数据库中查询数据,该数据库正在拉取我系统上观察到的每个端口的连接数列表。我尝试使用matplotlib将其绘制成简单的条形图。

到目前为止,我使用了以下代码:

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

当我运行上述操作时,数据从DB中检索成功并生成图表。但是,图表并不是我所期待的。例如,在x轴上,它绘制0到5005之间的所有值。我正在寻找它以仅显示dst_ports中的值。我尝试过使用xticks,但这也不起作用。

我在上面的代码中包含了一些示例数据,我已经注释了这些数据可能有用。

此外,以下是上述代码输出图表的示例:

graph without xticks

使用xticks时也是一个grpah:

graph using xticks

1 个答案:

答案 0 :(得分:4)

您需要按np.arange()创建一些xdata:

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

这是输出:

enter image description here