2017-02-12 90 views
0

次要情节,我有两个文件作为输入,看起来如下:情节Seaborn Barplots在与Python

col1 col2 
A B 
C C 
B A 
A A 
A C 
C A 
B B 

含义,我有两列用字母,用空格隔开。我想绘制这些字母出现的次数,每个字段在它自己的barplot中。假设这两个文件具有不同的字母分布。

这是代码:

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() 

结果应该是一个图像,其中,I具有以下barplots作为次要情节:

--------------------------------------- 
|     |     | 
|     |     | 
| barplot col1 | barplot col2 | 
|  file1  |  file1  | 
|     |     | 
--------------------------------------| 
|     |     | 
|     |     | 
| barplot col1 | barplot col2 | 
|  file2  |  file2  | 
|     |     | 
--------------------------------------- 

因此,每个条的高度应当对应于数的每封信。

直到现在的问题是,在每个子图中的酒吧看起来完全不同,我无法找出原因。请让我知道,如果我可以提供更多信息。

回答

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 
+0

你完全右我有不同的数据,并调整了在夜间的新数据文件的代码,而无需运行它们。对不起。我调整了我的代码,但它仍然不起作用。在左上角,我有几千个酒吧,在右上角只有几个酒吧(这是不正确的,因为在这两个文件中约有10万行)。 –

+0

我希望你明白我们需要根据我们在这里提供的信息来讨论这个问题。因此,如果您的数据与您在问题中显示的数据有所不同,那么很难为您提供帮助。然后,您需要创建一个新的[MCVE],将数据量减少到可以在此分享的数量,但仍然会重现此问题。 – ImportanceOfBeingErnest