上述代码中,柱状图横坐标如何全部显示呢
时间: 2024-02-28 18:55:30 浏览: 107
如果柱状图的横坐标较多,可能会出现横坐标标签重叠的情况。可以通过以下两种方式来解决:
1. 适当调整图像大小或字体大小,使得标签能够全部显示在图像中;
2. 采用倾斜或旋转标签的方式,使得标签不会重叠。
以下是第二种方式的实现示例代码:
```python
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx")
edges = []
for i in range(len(df)):
edge = {
"id": df.loc[i, "边的编号"],
"tail": df.loc[i, "边的尾节点"],
"head": df.loc[i, "边的头节点"],
"length": df.loc[i, "长度"],
"capacity": df.loc[i, "容量"]
}
edges.append(edge)
plt.figure(figsize=(15,15))
G = nx.DiGraph()
for edge in edges:
G.add_edge(edge["tail"], edge["head"], weight=edge["length"])
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.5)
plt.show()
all_pairs = dict(nx.all_pairs_dijkstra_path_length(G))
rows = []
for start_node, dist_dict in all_pairs.items():
for end_node, dist in dist_dict.items():
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': dist})
df_result = pd.DataFrame(rows)
df_result.to_excel('all_pairs.xlsx', index=False)
# 计算每个节点到其他节点的平均最短距离
avg_dists = []
for node in G.nodes():
dist_sum = 0
for dist in all_pairs[node].values():
dist_sum += dist
avg_dist = dist_sum / len(G.nodes())
avg_dists.append(avg_dist)
# 画柱状图,并旋转标签
plt.bar(G.nodes(), avg_dists)
plt.title("每个节点到其他节点的平均最短距离")
plt.xlabel("节点")
plt.ylabel("平均最短距离")
plt.xticks(rotation=90) # 旋转标签
plt.tight_layout() # 自动调整子图参数,使之填充整个图像区域
plt.show()
```
在上述代码中,我们通过`plt.xticks(rotation=90)`将标签旋转了90度,使得标签不会重叠。同时,我们还使用了`plt.tight_layout()`来自动调整子图参数,从而使得图像更加美观。
阅读全文