在matplotlib中的循环内绘制数据后设置颜色条

时间:2017-08-03 12:14:50

标签: python matplotlib colorbar

我想在tricontourf中使用matplotlib绘制一些有限元结果。为此,需要创建一个for循环来计算每个元素节点处的数据(类似于MATLAB中的fill命令)。这很好用,但问题在于colorbar的显示。它只显示最后一个元素的值(在循环结束后),它不包括整个域的值。

因此,有没有办法“累积”tricontourf的数据,以便颜色栏包含整个域的值,或者可能是一种操纵colorbar的方法呢?我尝试使用contour_sets.append()附加数据,然后将其用作colorbar的输入,但它不起作用。

代码如下所示:

# nodes and coordinates 
IEN  = np.array([[1,2,5,6],[2,3,4,5],[5,4,9,8],[6,5,8,7]])   # nodes vs elements
xx   = np.array([1, 2, 3, 3, 2, 1, 1, 2, 3])            # x coordinates
yy   = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3])            # y coordinates
zz   = np.array([50, 40, 30, 45, 20, 30, 30, 15, 10])   # magnitude
nen,nfe = np.shape(IEN)     # nodes per element, number of elements

#contour_sets = []
fig = plt.figure(1)
for e in range(nfe):
   idx = np.squeeze(IEN[:,e]-1)   # take the element nodes
   x   = xx[idx]                  # x coordinates of element e
   y   = yy[idx]                  # y coordinates of element e
   z   = zz[idx]                  # magnitude values of element e

   # additional node in the middle to be able to use tricontourf
   x5  = np.mean(x)               # x coordinate 
   y5  = np.mean(y)               # y coordinate 
   z5  = np.mean(z)               # magnitude value

   # set up the triangle nodes (rectangular element as two triangles)
   triangles = np.array([ [ 2, 4, 1 ], 
                          [ 2, 3, 4 ], ]) -1      

   # insert the additional middle node to the coordinates
   xt = np.insert(x,nen,[x5]).squeeze()       
   yt = np.insert(y,nen,[y5]).squeeze()      
   zt = np.insert(z,nen,[z5]).squeeze()  

   # plot the data           
   fil = plt.tricontourf(xt, yt, triangles, zt, norm=plt.Normalize(vmax=zz.max(), vmin=zz.min()), cmap=cm.pink) 
   #contour_sets.append(fil)

# organize the plot       
cb = plt.colorbar(fil, shrink=0.95, aspect=15, pad = 0.05)
cb.ax.yaxis.set_offset_position('left')                         
cb.update_ticks()
plt.xticks(np.arange(1,3.1,0.5))
plt.yticks(np.arange(1,3.1,0.5))
plt.xlim(1, 3)
plt.ylim(1, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.tight_layout()

给出了这个图(为了澄清目的而编辑): The colorbar only shows the values of zz asociated to the element 4

0 个答案:

没有答案