通過python讀取txt文件和繪制柱形圖的實現代碼

目的

臨床數據的記錄時間對應標簽(逗號後面的數字)記錄在txt文件裡,要把標簽轉換為3類標簽,並且計算出每個標簽的分別持續時間,然後繪制成柱形圖方便查閱。

小難點分析:

(1)txt的切割讀取對應內容  

 (2)時間差計算

txt文件如圖:

使用效果

首先將原始txt轉換為  左列新標簽 右列持續時間

繪制為柱形圖

為瞭直觀,每次隻最多顯示 2個小時,同時橫坐標還是按照臨床的記錄時間順序。

代碼實現

# -*- coding: utf-8 -*-
 
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
 
font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12)
address = "D:/XXXXXX/"
patient = "XXXXX"
year = '2020' # or 2020
txt_address = address + patient + "/timetable.txt"
filename = address + patient + "/newTimeTable.txt" # 保存的txt地址
 
# 讀取txt的相應內容
def showLabel():
  content = []
  label = []
  rawtime = []
 
  with open(txt_address, 'r', encoding="utf-8") as f:
    lines = f.readlines() # 返回的是列表
 
  print("文件的行數:%d" % len(lines))
 
  for line in lines:
    content_value = line.split(sep=',') # 分為[0]和[1]
    time_value = content_value[0].split(sep=year)
    content_value = content_value[1].split(sep='\n')
    temp_time = year + time_value[-1]
    rawtime.append(temp_time)
    content.append(content_value[0])
 
  # 去掉第一行的line和轉換label
  for i in range(1, len(lines)): # range是左閉右開
    number = int(content[i])
    if number == 4:
      label_value = 1 # label 1 表示癲癇發作
    elif number == 1:
      label_value = 0 # label 0 表示數據缺失
    else:
      label_value = -1 # label -1 表示非癲癇發作
    label.append(label_value)
 
  del rawtime[0] # 去掉第一行的line
  length = len(lines)
  return label, rawtime, length
 
# 計算時間差
def getTimeSpan(new_label,time,length):
  time_span = []
  time_label = []
  temp = datetime.strptime(time[0], "%Y-%m-%d  %H:%M:%S")
  for i in range(0, length - 2):
    if new_label[i] != new_label[i + 1]:
      end_time = datetime.strptime(time[i + 1], "%Y-%m-%d  %H:%M:%S")
      diff = end_time - temp
      temp = end_time
      # time_span.append(diff) 標準化時間
      time_span.append(round(diff.total_seconds() / 60, 2)) # 保留兩位小數
      time_label.append(new_label[i])
 
  return time_span, time_label
 
# 畫圖,按照標簽內容給圖上色
def showTimeandLabel(time_span,time_label):
  Yanse = []
  for i in time_label:
    if i == 0:
      yanse = 'blue'
    elif i == -1:
      yanse = 'gray'
    else:
      yanse = 'red'
    Yanse.append(yanse)
 
  plt.bar(range(len(time_span)), time_span, width=0.8, tick_label=time_label, color=Yanse)
  plt.xlabel('標簽', fontproperties=font_set)
  plt.ylabel("持續時間(分鐘)", fontproperties=font_set)
  plt.title("patient: " + patient, size=20)
 
  plt.ylim(0, 120)
  plt.show()
 
# 保存到txt
def txtSave(time_span, time_label):
  # w:向文件中寫入內容時,會先清空原文件中的內容,
  with open(filename, 'w', encoding="utf-8") as f:
    line_number = len(time_label)
    for i in range(line_number):
      f.write(str(time_label[i])+"              "+str(time_span[i]))
      f.write("\n")

def main():
  new_label, time, length = showLabel()
  time_span, time_label = getTimeSpan(new_label, time, length)
  txtSave(time_span, time_label)
  showTimeandLabel(time_span, time_label)
 
if __name__ == '__main__':
  main()

到此這篇關於通過python讀取txt文件和繪制柱形圖的文章就介紹到這瞭,更多相關python繪制柱形圖內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: