我在字典中有特定的值,从高到低排序,但最多可以有一千或更多的值。如果数字介于1-10之间并且给出图形的输出与dict中的前1-10个最高值,那么如何进行用户输入。因此,如果他们输入3,它将绘制3个最高值等...感谢高级
from collections import Counter
from scipy import *
from matplotlib.pyplot import *
import matplotlib.pyplot as plot
frequency1 = Counter({'1':100,'2':400,'3':200,'4':300,})
response1 = input("How many top domains from source? Enter a number between 1-10: ")
if response1 == "1":
if len(frequency1) >= 1:
print("\nTop 1 most is:")
for key, frequency1_value in frequency1.most_common(1):
print("\nNumber:",key,"with frequency:",frequency1_value)
########Graph for this output
x = [1,2]
y = [frequency1_value,0]
figure(1)
ax = plot.subplot(111)
ax.bar(x,y,align='center', width=0.2, color = 'm')
ax.set_xticklabels(['0', '1'])
xlabel("This graph shows amount of protocols used")
ylabel("Number of times used")
grid('on')
################################## END GRAPH
else:
print("\nThere are not enough domains for this top amount.")
if response1 == "2":
if len(frequency1) >= 2:
print("\nTop 2 most is:")
for key, frequency1_value in frequency1.most_common(2):
print("\nNumber:",key,"with frequency:",frequency1_value)
########Graph for this output
x = [1,2,3]
y = [frequency1_value,frequency1_value,0]
figure(1)
ax = plot.subplot(111)
ax.bar(x,y,align='center', width=0.2, color = 'm')
ax.set_xticklabels(['0', '1','','2'])
xlabel("This graph shows amount of protocols used")
ylabel("Number of times used")
grid('on')
################################## END GRAPH
else:
print("\nThere are not enough domains for this top amount.")
答案 0 :(得分:1)
下面的代码将创建字典中值的排序列表,然后绘制最大数字的相应图表,具体取决于用户输入。
import numpy as np
import matplotlib.pyplot as plt
d = {'1':100,'2':400,'3':200,'4':300,}
vals = sorted(d.values(), reverse=True)
response = input("How many top domains from source? Enter a number between 1-10: ")
if response > 0 and response < len(vals)+1:
y = vals[:response]
print ("\nTop %i most are:" %response)
print (y)
x = np.arange(1,len(y)+1,1)
fig, ax = plt.subplots()
ax.bar(x,y,align='center', width=0.2, color = 'm')
ax.set_xticks(x)
ax.set_xticklabels(x)
ax.set_xlabel("This graph shows amount of protocols used")
ax.set_ylabel("Number of times used")
ax.grid('on')
else:
print ("\nThere are not enough domains for this top amount.")
plt.show()
例如,如果用户在代码中输入3,则会生成以下图表并输出:
Top 3 most are:
[400, 300, 200]