如何在Python中打印直方图的y轴值?

时间:2014-10-17 13:02:42

标签: python plot histogram

我正在用Python打印直方图。但是对于我的生活,我无法弄清楚如何以100为增量打印y轴值(与我的x轴值类似)。

这是我的工作代码:

#!/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 

我错过了什么?

1 个答案:

答案 0 :(得分: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