从文件中提取值以使用matplotlib创建条形图

2024-05-23 17:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些使用matplotlib创建此图的帮助

这是从中提取事件id和计数的位置:

this is where the event id and the count are being extracted from

我需要创建一个图表。为此,我尝试了一些代码,但我不断出错,因为有列表要提取,老实说,我很困惑,这就是我迄今为止所做的代码:

def plotnew():
    event = []
    eventcount = []

    with open("path here", 'r') as visualise:
        for line in visualise:
            if line.startswith("Event ID: "):
                event.append(line.split([2]))
            elif line.startswith("Count:"):
                eventcount.append(int(line.split()[2]))

    plt.barh(event, eventcount)
    plt.xlabel('Event Count')
    plt.ylabel('Event ID')
    plt.title('EventID Count')
    plt.tight_layout()
    plt.show()

我曾尝试在行分割后添加[3]以获得计数值或事件id,但我一直在到处出现错误,我很困惑


Tags: 代码eventidvisualisematplotlibcountline事件
1条回答
网友
1楼 · 发布于 2024-05-23 17:49:00

下面的代码模拟通过StringIO读取文件,使示例代码自我包含。在代码中,您可以继续读取文件

对于文件中的每一行,代码首先测试它是否有有用的信息,这里测试行长度至少为10。然后,检查行的开头:如果行以"Event ID:"开头,我们分割行并将3rd部分带到eve。如果行以"Event Count:"开头,则3rd部分将转换为整数并追加到eventcount

import matplotlib.pyplot as plt
from io import StringIO

file_contents = '''
Event ID: 1102
Event Count: 15

Event ID: 4611
Event Count: 2

Event ID: 4624
Event Count: 46

Event ID: 4634
Event Count: 1
'''

eve = []
eventcount = []

# with open("path", 'r') as visualise: # when really reading from a file
with StringIO(file_contents) as visualise: # when mimicking a file with a string
    for line in visualise:
        if len(line) > 10:
            if line.startswith("Event ID:"):
                eve.append(line.split()[2])
            elif line.startswith("Event Count:"):
                eventcount.append(int(line.split()[2]))

plt.barh(eve, eventcount, color='springgreen')
plt.xlabel('Event Count')
plt.ylabel('Event ID')
plt.title('EventID Count')
plt.tight_layout()
plt.show()

barh plot

相关问题 更多 >