Matplotlib 在保存时将两个单独的图形压缩为一个

Matplotlib condenses two separate figures into one upon saving them

我是 Python 的新手。当运行这几行代码时,我希望保存两个单独的数字。

图号1:

#3) Create the graph
N=int(raw_input('Number of nodes (sqrt): '))
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() ) #Dictionary of all positions
labels = dict( ((i, j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.draw_networkx(G, pos=pos, labels=labels,with_labels=False, node_size=10)
#Plot the graph
plt.axis('off')
title_string=('Lattice Network') 
subtitle_string=(''+str(N)+'x'+str(N)+' = '+str(N*N)+' nodes')
plt.suptitle(title_string, y=0.99, fontsize=17)
plt.title(subtitle_string, fontsize=8)
plt.savefig('100x100_lattice.png', dpi=1000,bbox='tight') #Figure no. 1
plt.close()

图号2:

#4) Plot the degree distribution
for data_dict in node_degree.values():
    x=node_degree.keys()
    y=node_degree.values()
from collections import Counter
occ=Counter(y)
for data_dict in occ.values():
    plotx=occ.keys()
    ploty=occ.values()
Pk=numpy.zeros((len(ploty)))
for i in range(0, len(ploty)):
    Pk[i]=numpy.around(ploty[i]/(N*N),3)
plt.scatter(plotx,Pk,color='red', edgecolors='darkred')
plt.show() 
plt.xlabel('Node degree k')
plt.ylabel('P(k)')
plt.xlim(0,10,1)
plt.xticks(numpy.arange(0, 11, 1.0))
plt.ylim(0,1) 
plt.yticks(numpy.arange(0, 1, 0.1))
title_string=('Degree Distribution')
subtitle_string=('Lattice, '+str(N)+'x'+str(N)+' nodes') 
plt.suptitle(title_string, y=0.99, fontsize=17)
plt.title(subtitle_string, fontsize=9)
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom='on',      # ticks along the bottom edge are off
    top='on',         # ticks along the top edge are off
    labelbottom='on')
plt.savefig('100x100_lattice_Degree_Distrib.png', dpi=1000,bbox='tight') #Figure no. 2
plt.close()

相反,我在视觉上得到的是:

我的问题。右边的图像(在代码中,Figure no. 2)是正确的。左边的 (Figure no. 1) 是错误的,因为它应该只显示您看到的规则结构而不是红点,红点显然来自第二张图片。我的 plt.show 电话一定有问题,但我找不到答案。感谢您的帮助!

问题是你第二个图中的 plt.scatter() 正在绘制你第一个图中创建的图形,对吧?只需在调用第二个图中的 plt.scatter() 之前添加对 plt.figure() 的调用。这应该可以解决您的问题。