2015-05-09 73 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爲你的幫助,感謝它! –