【问题标题】:How to print y-axis values of histogram plot in Python?如何在 Python 中打印直方图的 y 轴值?
【发布时间】:2014-10-17 13:02:42
【问题描述】:

我正在用 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 

我错过了什么?

【问题讨论】:

  • 您可能想使用numpy.histogram 而不是自己计算。
  • 这样会更容易,是的。但这是针对我们不能使用非本地模块的类分配。

标签: python plot histogram


【解决方案1】:

试试这个?

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

【讨论】:

  • 我没有看到行值。
  • 其实,我认为这是我的 y_max 值的结果。
猜你喜欢
  • 2020-12-26
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多