在直方图上打印 y 轴并使用 dict 函数作为输入
如何使用另一个函数中的字典作为下面 histo 的输入参数,并使用字典值标记 y 轴(除了 x 轴)?或者有没有比这段代码更简单的替代方案?
def histo(his_dict = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, 8:1} ):
x_max = max(his_dict.keys()) + 2 #get maximum value of x
y_max = max(his_dict.values()) + 2 #get minimum value of y
# print line per line
print ('^')
for j in range(y_max, 0, -1):
s = '|'
for i in range(1, x_max):
if i in his_dict.keys() and his_dict[i] >= j:
s += '*'
else:
s += ' '
print (s)
# print x axis
s = '+'
for i in range(1, x_max):
s += '---'
s += '>'
print (s)
# print indexes
s = ' '
for i in range(1, x_max):
s += ' %d ' % i
print (s)
histo()
How can I use a dict from another function as input argument to histo below, and label the y axis with dict values (in addition to the x-axis)? Or is there a simpler alternative to this code at all?
def histo(his_dict = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, 8:1} ):
x_max = max(his_dict.keys()) + 2 #get maximum value of x
y_max = max(his_dict.values()) + 2 #get minimum value of y
# print line per line
print ('^')
for j in range(y_max, 0, -1):
s = '|'
for i in range(1, x_max):
if i in his_dict.keys() and his_dict[i] >= j:
s += '*'
else:
s += ' '
print (s)
# print x axis
s = '+'
for i in range(1, x_max):
s += '---'
s += '>'
print (s)
# print indexes
s = ' '
for i in range(1, x_max):
s += ' %d ' % i
print (s)
histo()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我是你,我会用 pylab 绘制直方图。
并且不传递字典,而是传递原始值列表。
y 轴将自动计算。
If I were you, I would just draw the histogram with pylab.
And instead of passing a dict, just pass a raw list of values.
The y-axis will be computed automatically.