如何在Python中打印直方图的y轴值?(How to print y

编程入门 行业动态 更新时间:2024-10-22 20:30:36
如何在Python中打印直方图的y轴值?(How to print y-axis values of histogram plot in Python?)

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

我错过了什么?

I'm printing a plot of a histogram in Python. But for the life of me, I can't figure out how to print the y-axis values in increments of 100 (in a similar manner to my x-axis values).

Here's my working code:

#!/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.")

This prints everything but my y-axis values:

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

What am I missing?

最满意答案

试试吧?

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基于您的样本, 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

try this perhaps?

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

this is a stripped down version (if line%2 ==0 based on your samples) and it outputs:

$ 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

更多推荐

本文发布于:2023-08-06 10:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:直方图   如何在   print   Python   轴值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!