2014-10-17 2 views
0

Я печатаю график гистограммы в Python. Но для жизни я не могу понять, как печатать значения оси y с шагом 100 (аналогично моим значениям по оси x).Как печатать значения оси Y графика гистограммы в Python?

Вот мой рабочий код:

#!/usr/local/bin/python3 

import math 
from sys import argv 
from string import punctuation 
from collections import Counter as counter 
from operator import itemgetter 

def roundup(x): 
    """ Rounds an integer up to the nearest 100 value """ 
    rounded_value = int(math.ceil(x/100.0)) * 100 
    return rounded_value 

def histogram(file_data): 
    """ Plots file data on a graph """ 

    x_max = max(file_data.keys()) + 1 
    y_max = max(file_data.values()) + 1 

    y_bin = [] 
    for value in range(roundup(y_max), 0, -100): 
     y_bin.append(value) 

    for line in range(y_max, 0, -20): 
     s = '{:>8}'.format('|') 

     for i in range(1, x_max, 1): 
      if i in file_data.keys() and file_data[i] >= line: 
       s += '{}'.format('***') 
      else: 
       s += '{}'.format(' ') 
     print('{}'.format(s)) 

    s = '{:>6}'.format('0 ') 
    for i in range(1, x_max + 1, 1): 
     s += '-+-' 
    print('{}'.format(s)) 

    s = '{:>8}'.format('|') 
    for i in range(1, x_max, 1): 
     s += '{:>3}'.format(i) 
    print('{:>5}'.format(s)) 

def strip_punc(text): 
    """ This function strips punctuation from a 
    string passed as an argument. 
    """ 
    # Keep '&' since it counts as a word  
    # Loop through text and remove punctuation 
    for punc in punctuation.replace("&", ""): 
     text = text.replace(punc, "") 

    return text 


def compute_text(filename): 
    """ This function reads input from a file, 
    splits the words into a list, and computes 
    the length of each word. It then prints a 
    table showing the word count for each 
    of the word lengths. 
    """ 
    # Open our file 
    try: 
     with open(filename, 'r') as f: 
      # Read the file 
      data = f.read() 

      # Strip the punctuation 
      data = strip_punc(data) 

      # Print the headers 
      print('{:>7}{:>10}'.format('Length', 'Count')) 

      # Use counter to get a dictionary of our lengths and values from data 
      length_count_lst = counter([len(word) for word in data.lower().split()]) 

      # Create a sorted list (by length) of tuples 
      sorted_lst = sorted(length_count_lst.items(), key=itemgetter(0)) 

      # Print our items 
      for item in sorted_lst: 
       print('{!s:>8}{!s:>10}'.format(item[0], item[1])) 

     histogram(dict(sorted_lst)) 
    except FileNotFoundError: 
     print("Your file cannot be found.") 
    #except TypeError: 
    # print("You didn't enter a file.") 
    #except: 
    # print("Unknown error.") 

if __name__ == "__main__": 

    try: 
     filename_input = argv[1] 
     compute_text(filename_input) 
    except IndexError: 
     print("You didn't enter a filename.") 

Это печатает все, кроме моих значений по оси Y:

Length  Count                          
     1  17                          
     2  267                          
     3  267                          
     4  169                          
     5  140                          
     6  112                          
     7  99                          
     8  68                          
     9  61                          
     10  56                          
     11  35                          
     12  13                          
     13   9                          
     14   7                          
     15   2                          
     |                            
     | ******                          
     | ******                          
     | ******                          
     | ******                          
     | *********                         
     | *********                         
     | ************                         
     | ***************                        
     | ******************                       
     | *********************                      
     | ***************************                     
     | ******************************                    
     |***************************************                   
    0 -+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-                 
     | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 

Что я упускаю?

+0

Вы можете использовать 'numpy.histogram' вместо вычисления его самостоятельно. – Ben

+1

Было бы проще, да. Но это для назначения класса, где мы не можем использовать неродные модули. –

ответ

0

попробуйте это, возможно?

for line in range(y_max, 0, -20): 
     if line%100 == 0: 
      s = '{:>8}'.format(str(line)+' |') # add 2 spaces so y-axis align with 0 
     else: 
      s = '{:>8}'.format('|') 

это урезанная версия (if line%2 ==0 на основе ваших образцов) и выводит:

$ python3 hist.py keys.txt 
Length  Count 
     1  12 
     2  13 
     3   5 
     5   1 
     6   1 
    14 |     
     | ***    
    12 |******    
     |******    
    10 |******    
     |******    
    8 |******    
     |******    
    6 |******    
     |*********   
    4 |*********   
     |*********   
    2 |*********   
     |********* ****** 
    0 -+--+--+--+--+--+--+- 
     | 1 2 3 4 5 6 
+0

Я не вижу значения строк. –

+0

На самом деле, я думаю, что это результат моего значения y_max. –

+0

это конечно работает. Да, если 100> y_max, это не будет напечатано – Anzel

Смежные вопросы