我有两个文件作为输入,如下所示:
col1 col2
A B
C C
B A
A A
A C
C A
B B
意思是,我有两列字母,用空格分隔。我想绘制这些字母的出现次数,每个列都在自己的条形图中。假设两个文件都有不同的字母分布。
这是代码:
from collections import Counter
from os.path import isfile, join
from os import listdir
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
inputDir = "/tmp/files/"
inputFiles = [ f for f in listdir(inputDir) if isfile(join(inputDir, f)) ]
fig, axes = plt.subplots(figsize=(6,6), ncols=2, nrows=len(inputFiles))
z=0
while inputFiles:
files = inputFiles[0]
inputFiles.remove(files)
c = Counter()
a = Counter()
x1 = []
y1 = []
x2 = []
y2 = []
with open(inputDir + files, "r") as f2:
for line in f2:
line = line.strip()
if line.split(" ")[0] != "col1":
c[str(line.split(" ")[0])] += 1
a[str(line.split(" ")[1])] += 1
try:
for cc in c:
x1.append(cc)
y1.append(c[cc])
row = z // 2
col = z % 2
ax_curr = axes[row, col]
sns.barplot(x1, y1, ax=ax_curr)
z+=1
for aa in a:
x2.append(aa)
y2.append(a[aa])
row = z // 2
col = z % 2
ax_curr = axes[row, col]
sns.barplot(x2, y2, ax=ax_curr)
z+=1
except:
continue
sns.plt.show()
结果应该是一张图片,我将以下条形图作为子图:
---------------------------------------
| | |
| | |
| barplot col1 | barplot col2 |
| file1 | file1 |
| | |
--------------------------------------|
| | |
| | |
| barplot col1 | barplot col2 |
| file2 | file2 |
| | |
---------------------------------------
因此每个条形的高度应与每个字母的数量相对应。
直到现在的问题是,每个子情节中的条形看起来完全不同,我无法找出原因。如果我能提供更多信息,请告诉我。
答案 0 :(得分:0)
虽然目前还不清楚这里的“完全”不同意味着什么,但可能需要在分割之前去除线条。否则,最后一列的值可能看起来像"B "
而不是"B"
。此外,我不确定为什么要尝试将字符串转换为c[int(line.split(" ")[0])] += 1
中的整数。这对我来说没什么意义。
尝试:
with open(inputDir + files, "r") as f2:
for line in f2:
line = line.strip()
if line.split(" ")[0] != "col1":
c[line.split(" ")[0]] += 1
a[line.split(" ")[1]] += 1