【问题标题】:Python display specific values on x-axis using matplotlibPython使用matplotlib在x轴上显示特定值
【发布时间】:2014-07-10 10:55:53
【问题描述】:

我正在从一个简单的 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 时也是一个 grpah:

【问题讨论】:

    标签: python graph matplotlib


    【解决方案1】:

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

    这是输出:

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 1970-01-01
      • 2018-05-20
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      相关资源
      最近更新 更多