2015-05-09 34 views
0

我有一个图形显示contourf图和另一个显示我之前制作的图,我想在同一图上绘制两幅图,我该怎么做? 这里是我的contourf情节代码:如何在同一图中绘制contourf和我的图形

import pylab as pl 
from pylab import * 
import xlrd 
import math 
import itertools 
from matplotlib import collections as mc 
import matplotlib.pyplot as plt 
import copy as dc 
import pyexcel 
from pyexcel.ext import xlsx 
import decimal 

x_list = linspace(0, 99, 100) 
y_list = linspace(0, 99, 100) 
X, Y = meshgrid(x_list, y_list, indexing='xy') 

Z = [[0 for x in range(len(x_list))] for x in range(len(y_list))] 
for each_axes in range(len(Z)): 
    for each_point in range(len(Z[each_axes])): 
     Z[len(Z)-1-each_axes][each_point] = power_at_each_point(each_point, each_axes) 

figure() 
CP2 = contourf(X, Y, Z, cmap=plt.get_cmap('Reds')) 
colorbar(CP2) 
title('Coverage Plot') 
xlabel('x (m)') 
ylabel('y (m)') 
show() 

这是我以前绘制的情节代码:

lc = mc.LineCollection(lines, linewidths=3) 
fig, ax = pl.subplots() 
ax.add_collection(lc) 
ax.autoscale() 
ax.margins(0.05) 

#The code blow is just for drawing the final plot of the building. 
Nodes = xlrd.open_workbook(Node_file_location) 
sheet = Nodes.sheet_by_index(0) 
Node_Order_Counter = range(1, sheet.nrows + 1) 
In_Node_Order_Counter = 0 
for counter in range(len(Node_Positions_Ascending)): 
    plt.plot(Node_Positions_Ascending[counter][0],  Node_Positions_Ascending[counter][1], marker='o', color='r', 
      markersize=6) 
    pl.text(Node_Positions_Ascending[counter][0],  Node_Positions_Ascending[counter][1], 
      str(Node_Order_Counter[In_Node_Order_Counter]), 
      color="black", fontsize=15) 
    In_Node_Order_Counter += 1 
#Plotting the different node positions on our plot & numbering them 
pl.show() 
+0

要在同一个图上绘制一个图和contourf图,您应该使用子图(参见[suplots demo](http://matplotlib.org/examples/pylab_examples/subplots_demo.html))。 – Flabetvibes

+0

请注意,您应该在代码中包含导入,因此我们不必猜测'pl','mc'等等。 – Ajean

+0

@Baptiste,但我不想把它们作为子图放在彼此的旁边,我想绘制彼此之间的图。 –

回答

1

没有你的数据,我们看不到什么情节应该看起来像,但我有一些一般性建议。

  1. 请勿使用pylab。如果您绝对必须使用它,请在其名称空间内使用它,并且不要执行from pylab import *。它使得代码非常潦草 - 例如,linspace和meshgrid实际上来自于numpy,但是当你使用pylab时很难说清楚。
  2. 对于复杂的绘图,请勿使用pyplot。相反,使用直接对象绘图接口。例如,为了使在等高线图上方的正常的情节,(比如你想做的事),你可以做到以下几点:
import numpy as np 
import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

x = np.linspace(1, 5, 20) 
y = np.linspace(2, 5, 20) 
z = x[:,np.newaxis] * (y[np.newaxis,:])**2 

xx, yy = np.meshgrid(x, y) 

ax.contourf(xx, yy, z, cmap='Reds') 
ax.plot(x, 0.2*y**2) 

plt.show() 

contour and line plot together

注意,我只用pyplot来创建图形和坐标轴,并显示它们。实际绘图是使用AxesSubplot对象完成的。

+0

这正是我想要的,但我可以问你一个性能提示问题吗? 如果我有一个100mx100m的大空间,我计算该空间每1米处的功率,以便在末尾获得该空间的contourf图。 我的代码在25分钟内运行,这是不令人满意的,所以你知道我可以做的一个提示,以减少运行时间? –

+1

有很多方法可以加速代码的运行速度,但它高度依赖于您正在执行的操作。关于我的头顶,我会说1)尽可能向量化你的操作以避免循环,2)可能降低你的网格分辨率(只计算每2米而不是1米) – Ajean

+0

我可以从这样做开始,谢谢@ Ajean为你的帮助,感谢它! –