如何通过比较从python中两个不同文本文件读取的数据来生成图?

时间:2020-08-07 07:45:26

标签: python plot

我有两个文本文件。第一个格式为:

K_1, 1
K_2, 2
J_1, 3
J_2, 4
J_3, 5
L_1, 6

第二个文件的格式为:

K_2, 6
K_1, 5
J_2, 4
J_3, 4
J_1, 5
L_1, 4

两个文件中的第一列都包含相同的字符串集,但是第二列是不同的,取值范围为1到6(最小值为1,最大值为6)。

我需要从这些文件中获取两个图...

第一个图将这些文本文件中的每个作为输入,并创建一个图形,在x轴上具有1,2,3,4,5,6个数字,在y上分别具有1s,2s,3s等计数-轴。因此,我想比较一个图中每个文件的第二列值。

在第二个图中,我需要列值之间的差异。也就是说,对于K_1,第一个文件中的值是1,第二个文件中的值是5。我需要计算它们与返回值4之间的绝对差(abs(1-5)= 4)。将针对同一字符串的两个值(此处为K_1)计算差异。最后,我需要在x轴上记录“无差值”,具有1差的值,具有2差的值,具有3差的值,具有4差的值以及具有5差的值。分别在y轴上计数。

有人可以帮我用python绘制吗?

1 个答案:

答案 0 :(得分:0)

import matplotlib.pyplot as plt
import collections

file_txt1 = open('your_file1_path_and_name.txt', 'r')
lines1 = [line.split(', ') for line in file_txt1.readlines()]
column1 = [line[0] for line in lines1]
values1 = [int(line[1]) for line in lines1]
nb_lines = len(column1)


file_txt2 = open('your_file2_path_and_name.txt', 'r')
lines2 = [line.split(', ') for line in file_txt2.readlines()]
column2 = [line[0] for line in lines2]
values2 = [int(line[1]) for line in lines2]


# Check if the lines names are the same for both files
if collections.Counter(column1) != collections.Counter(column2) :
  raise ValueError("files '{}' and '{}' don't have the same lines names".format(file_txt1.name, file_txt2.name))


# First plot
x = list(range(1,7))
y1 = [values1.count(i) for i in x]
y2 = [values2.count(i) for i in x]
plt.plot(x,y1, label = "file '{}'".format(file_txt1.name))
plt.plot(x,y2, label = "file '{}'".format(file_txt2.name))
plt.legend()
plt.title('Counts of numbers in each file')
plt.show()

# Second plot
values2_in_order = [values2[column2.index(line_name)] for line_name in column1] # Gives a list with the same elements as values2, but this time in the same order as values1
y3 = [abs(values1[i] - values2_in_order[i]) for i in range(nb_lines)]
plt.plot(column1, y3)
plt.title('Absolute differences of lines between both files')
plt.show()

# Third plot
y4 = [y3.count(i) for i in range(6)]
plt.plot(list(range(6)), y4)
plt.title('Counts of absolute differences')
plt.show()
相关问题