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

3 投票
1 回答
12557 浏览
提问于 2025-04-18 12:46

我正在从一个简单的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')

当我运行上面的代码时,数据成功从数据库中提取出来,并生成了一个图表。但是,这个图表并不是我预期的样子。比如,在x轴上,它显示了从0到5005的所有值。我希望它只显示在dst_ports中的值。我尝试使用xticks,但这也没有效果。

我在上面的代码中包含了一些示例数据,并把它们注释掉了,这可能会有帮助。

另外,这里有一个上面代码生成的图表输出示例:

没有xticks的图表

还有一个使用xticks时的图表:

使用xticks的图表

1 个回答

3

你需要用 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')

这是输出结果:

在这里输入图片描述

撰写回答