keysCount.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import time
  2. from tarfile import data_filter
  3. import pandas as pd
  4. import matplotlib.pyplot as plt
  5. from datetime import datetime
  6. from pandas.io.sas.sas_constants import dataset_length
  7. # 示例数据(一组数据即可)
  8. data = [
  9. {"time": 1114, "params": {"key1": 190, "key2": 328, "key3": 312}},
  10. {"time": 1113, "params": {"key1": 150, "key2": 318, "key3": 334}},
  11. {"time": 1112, "params": {"key1": 126, "key2": 299, "key3": 340}},
  12. {"time": 1111, "params": {"key1": 119, "key2": 270, "key3": 350}},
  13. {"time": 1110, "params": {"key1": 110, "key2": 200, "key3": 100}}
  14. ]
  15. class DataVisualizer:
  16. def __init__(self, data_list):
  17. self.data_list = data_list
  18. self.dfs = self._process_data_list()
  19. self.keys = self._get_keys() # 自动获取所有key
  20. # 添加中文字体配置
  21. self._setup_chinese_font()
  22. def _setup_chinese_font(self):
  23. """配置中文字体支持"""
  24. try:
  25. plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
  26. plt.rcParams['axes.unicode_minus'] = False
  27. except Exception as e:
  28. print(f"字体配置警告: {e}")
  29. def _process_data_list(self):
  30. """处理多个原始数据为DataFrame列表"""
  31. dfs = []
  32. print(self.data_list)
  33. for data in self.data_list:
  34. df_data = []
  35. for item in data:
  36. row = {"time": item["time"]}
  37. row.update(item["params"])
  38. df_data.append(row)
  39. df = pd.DataFrame(df_data)
  40. df = df.sort_values('time') # 按时间升序排列
  41. dfs.append(df)
  42. return dfs
  43. def _get_keys(self):
  44. """自动获取所有key(即params中的键)"""
  45. if self.dfs:
  46. return list(self.dfs[0].columns) # 假设所有数据的key一致
  47. return []
  48. def get_data_summary(self):
  49. """生成多个数据数组的统计摘要"""
  50. summaries = []
  51. for df in self.dfs:
  52. summary = {'数据点数量': len(df), '时间范围': f"{df['time'].min()} - {df['time'].max()}"}
  53. for key in self.keys:
  54. start = df[key].iloc[0]
  55. end = df[key].iloc[-1]
  56. diff = end - start
  57. rate = (diff / start) * 100 if start != 0 else 0
  58. summary[f'{key}变化'] = f"{start} → {end} (Δ{diff}, {rate:.1f}%)"
  59. summaries.append(summary)
  60. return summaries
  61. def convertTime(timesMs):
  62. local_time = time.localtime(timesMs)
  63. return f"{local_time.tm_hour:02d}:{local_time.tm_min:02d}"
  64. def create_individual_key_plots11(self):
  65. """为每个key单独生成一个独立图表"""
  66. for key in self.keys:
  67. if key == 'time':
  68. continue
  69. plt.figure(figsize=(10, 6))
  70. for i, df in enumerate(self.dfs):
  71. plt.plot(df['time'], df[key],
  72. marker='o', linewidth=2, markersize=8,
  73. label=f'数据组{i + 1} - {key}变化趋势')
  74. print('xx = ' , df['time'])
  75. print('mm = ', df[key])
  76. for j, (time, value) in enumerate(zip(df['time'], df[key])):
  77. plt.annotate(f'{value}', (time, value), textcoords="offset points", xytext=(0, 10), ha='center', fontsize=12)
  78. plt.xlabel('时间', fontsize=12)
  79. plt.ylabel('参数值', fontsize=12)
  80. plt.title(f'{key}在不同数据组随时间的变化对比', fontsize=14, fontweight='bold')
  81. plt.legend()
  82. plt.grid(True, alpha=0.3)
  83. plt.xticks(self.dfs[0]['time'])
  84. plt.tight_layout()
  85. plt.show()
  86. def create_individual_key_plots(self):
  87. """为每个key单独生成一个独立图表,时间戳转换为年月日时分秒格式"""
  88. for key in self.keys:
  89. if key == 'time':
  90. continue
  91. plt.figure(figsize=(10, 6))
  92. # 存储所有格式化后的时间,用于统一x轴刻度
  93. all_formatted_times = []
  94. for i, df in enumerate(self.dfs):
  95. # 将时间戳转换为年月日时分秒格式
  96. formatted_times = []
  97. for timestamp in df['time']:
  98. # 假设时间戳为整数或浮点数
  99. dt_obj = datetime.fromtimestamp(timestamp / 1000)
  100. formatted_time = dt_obj.strftime("%H:%M:%S")
  101. formatted_times.append(formatted_time)
  102. # 如果是第一个数据组,保存格式化后的时间用于x轴刻度
  103. if i == 0:
  104. all_formatted_times = formatted_times
  105. # 使用格式化后的时间进行绘图
  106. plt.plot(formatted_times, df[key],
  107. marker='o', linewidth=2, markersize=8,
  108. label=f'数据组{i + 1} - {key}变化趋势')
  109. print('原始时间戳 = ', df['time'])
  110. print('格式化时间 = ', formatted_times)
  111. print('数值数据 = ', df[key])
  112. # 为每个数据点添加标注
  113. for j, (formatted_time, value) in enumerate(zip(formatted_times, df[key])):
  114. plt.annotate(f'{value}',
  115. (formatted_time, value),
  116. textcoords="offset points",
  117. xytext=(0, 10),
  118. ha='center',
  119. fontsize=12)
  120. plt.xlabel('时间', fontsize=12)
  121. plt.ylabel('参数值', fontsize=12)
  122. plt.title(f'{key}在不同数据组随时间的变化对比', fontsize=14, fontweight='bold')
  123. plt.legend()
  124. plt.grid(True, alpha=0.3)
  125. # 设置x轴刻度为格式化后的时间
  126. plt.xticks(all_formatted_times, rotation=45)
  127. plt.tight_layout()
  128. plt.show()
  129. def show(data1):
  130. # 创建数据数组(示例:1个数据数组)
  131. data_list = [data1]
  132. # 创建可视化器实例
  133. visualizer = DataVisualizer(data_list)
  134. print("=" * 50)
  135. print("数据表格展示")
  136. print("=" * 50)
  137. for i, df in enumerate(visualizer.dfs):
  138. print(f"数据组{i + 1}表格:")
  139. print(df)
  140. print()
  141. print("=" * 50)
  142. print("数据统计摘要")
  143. print("=" * 50)
  144. summaries = visualizer.get_data_summary()
  145. for i, summary in enumerate(summaries):
  146. print(f"数据组{i + 1}统计摘要:")
  147. for key, value in summary.items():
  148. print(f" {key}: {value}")
  149. print()
  150. # 为每个key单独生成图表
  151. print("正在生成每个key的独立对比图表...")
  152. visualizer.create_individual_key_plots()
  153. '''
  154. if __name__ == "__main__":
  155. main()
  156. '''