我想在我制作的直方图中将值放在y轴上。 我希望每100个值例如放“100- |” ,“200- |”等等 我的代码是:
def histogram(lenghts):
xmax=max(lengths.keys())
ymax=max(lenght.values())
symbol=""
indexing=""
for j in range(ymax,-1,-10):
symbol="{0}".format("|")
for v in range(ymax,-1,-100):#here i try to put the values
print("{0}{1:<4}".format(v,"-|"))
#fill histogram
for i in range(1,xmax):
if i in lengths.keys() and lengths[i]>=j:
symbol+="***"
else:
symbol+=" "
print(symbol)
#x-axis
symbol="{:>5}".format("-+-")
for i in range(1,xmax):
symbol+="+--"
print(symbol)
#indexing x-axis
for i in range(1,xmax):
indexing+="{:>6}".format(i)
print(indexing)
return
我得到的值只是相同的值,例如“67- |,167- |,267- |”。 我无法想象如何正确行事!
答案 0 :(得分:1)
这里有一个有效的代码。诀窍在模块运算符中,当y轴是接近一百的数字时,用于绘制y轴的比例数。 您的代码中还有一些其他小问题,包含变量名称。
def histogram(lenghts):
xmax = max(lenghts.keys())
ymax = max(lenghts.values())
symbol = ""
indexing = ""
step = 10
for j in range(ymax, -1, -step):
if j % 100 < step:
symbol = "{0:>3}{1:>3}".format(j, "-|")
else:
symbol = "{0:>3}{1:>3}".format(" ", "|")
#fill histogram
for i in range(1, xmax+1):
if i in lenghts.keys() and lenghts[i] >= j:
symbol += "***"
else:
symbol += " "
print(symbol)
#x-axis
symbol= "{0:>8}".format("-+--")
for i in range(1, xmax+1):
symbol += "+--"
print(symbol)
#indexing x-axis
indexing = " "
for i in range(1, xmax+1):
indexing += "{0:>3}".format(i)
print(indexing)
lenghts = {4:104, 6:257, 10:157}
histogram(lenghts)