简体   繁体   中英

Histogram with matplotlib

I am trying to represent the distribution of degrees of a network with a histogram of matplotlib. The data structure I want to represent is similar to the dictionary below:

dic = {'COMBUSTÍVEIS E LUBRIFICANTES.': 214,
'Emissão Bilhete Aéreo': 234,
'LOCAÇÃO OU FRETAMENTO DE VEÍCULOS AUTOMOTORES': 183,
'MANUTENÇÃO DE ESCRITÓRIO DE APOIO À ATIVIDADE PARLAMENTAR': 201,
'SERVIÇOS POSTAIS': 124,
'TELEFONIA': 226,
'DIVULGAÇÃO DA ATIVIDADE PARLAMENTAR.': 188,
'FORNECIMENTO DE ALIMENTAÇÃO DO PARLAMENTAR': 14,
'CONSULTORIAS PESQUISAS E TRABALHOS TÉCNICOS.': 106,
'SERVIÇO DE SEGURANÇA PRESTADO POR EMPRESA ESPECIALIZADA.': 27,
'ASSINATURA DE PUBLICAÇÕES': 11,
'PASSAGENS AÉREAS': 21,
'HOSPEDAGEM EXCETO DO PARLAMENTAR NO DISTRITO FEDERAL.': 36}

With the code below, I count and group the grades according to their respective values:

degree_sequence = sorted([d for n, d in dic.items()], reverse=True)
degree_count = collections.Counter(degree_sequence)
deg, cnt = zip(*degree_count.items())

And plot the histogram:

fig, ax = plt.subplots()
plt.bar(deg, cnt, width=0.80, color='b')
plt.title("Degree Histogram")
plt.ylabel("Count")
plt.xlabel("Degree")
ax.set_xticks([d + 0.4 for d in deg])
ax.set_xticklabels(deg)
plt.axes([0.4, 0.4, 0.5, 0.5])
Gcc = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0]
plt.axis('off')
plt.show()

Result:

在此处输入图片说明

The low-value view of the dictionary is already very poor, the x-axis values ​​are very close to each other, which makes it difficult to understand. In the original work, the dictionary has approximately 300 key-values, which considerably worsens the visualization. So what can I do to improve the visualization and space the x-axis values?

Instead of using deg values as the x-coordinates for the bar plot, you can use a range(len(deg)) which generates 0, 1, 2, 3, etc. as the x-values. Then, you can replace the tick labels with the actual deg values

fig, ax = plt.subplots()
plt.bar(range(len(deg)), cnt, width=0.6, color='b')
plt.title("Degree Histogram")
plt.ylabel("Count")
plt.xlabel("Degree")
ax.set_xticks(range(len(deg)))
ax.set_xticklabels(deg)
plt.axes([0.4, 0.4, 0.5, 0.5])
plt.axis('off')
plt.show()

You can also combine the above two lines for setting x-ticks into one as

plt.xticks(range(len(deg)), deg)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM