2017-06-27 23 views
1

假設我有以下代碼(的matplotlib gridspec tutorial修改版本)劇情副區在單獨的圖軸在matplotlib

import matplotlib.pyplot as plt 

def make_ticklabels_invisible(fig): 
    for i, ax in enumerate(fig.axes): 
     ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center") 
     for tl in ax.get_xticklabels() + ax.get_yticklabels(): 
      tl.set_visible(False) 


plt.figure(0) 
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3) 
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2) 
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2) 
ax4 = plt.subplot2grid((3,3), (2, 0)) 
plt.subplot2grid((3,3), (2, 1)) # OOPS! Forgot to store axes object 

plt.suptitle("subplot2grid") 
make_ticklabels_invisible(plt.gcf()) 
plt.show() 

這導致

enter image description here

我怎樣才能「提取」 ax5和將其'全屏'繪製在單獨的圖中而不需要必須重新創建劇情?

+0

請發佈您正在使用的代碼來生成您在上面看到的圖。總是發佈你的代碼,這使得其他人更容易幫助你。 –

+0

感謝您的提示。我已經重新制定了這個問題。乾杯! – Milo

回答

2

我在官方文檔中找不到任何東西來備份我在說的內容,但我的理解是,將現有軸「克隆」到新圖上是不可能的。事實上,一個軸中定義的藝術家(線條,文字,圖例)可能不會添加到其他軸。 This discussion on Github may explain it to some degree

例如,試圖從上fig1定義爲在不同的圖中fig2一個軸的軸線添加一行引發錯誤:

import matplotlib.pyplot as plt 
fig1 = plt.figure() 
ax1 = fig1.add_subplot(111) 
line, = ax1.plot([0,1]) 
fig2 = plt.figure() 
ax2 = fig2.add_subplot(111) 
ax2.add_line(line) 
>>>RuntimeError: Can not put single artist in more than one figure` 

並試圖添加被畫在ax1所涉及的線第二軸線ax2相同圖引發錯誤:

fig1 = plt.figure() 
ax1 = fig1.add_subplot(121) 
line, = ax1.plot([0,1]) 
ax12 = fig1.add_subplot(122) 
ax12.add_line(line) 
>>>ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported 

我可以使最佳的建議是提取從軸喲數據你想複製,並手動繪製成一個新的軸對象,大小可以根據你的喜好。像下面的東西演示了這一點。請注意,這適用於通過ax.plot繪製的Line2D對象。如果數據是使用ax.scatter繪製的,那麼您需要稍微改變一些東西,並且我需要refer you here for instructions on how to extract data from a scatter

import matplotlib.pyplot as plt 
import numpy as np 

def rd(n=5): 
    # Make random data 
    return np.sort(np.random.rand(n)) 

fig1 = plt.figure() 
ax1 = fig1.add_subplot(111) 
# Plot three lines on one axes 
ax1.plot(rd(), rd(), rd(), rd(), rd(), rd()) 

xdata = [] 
ydata = [] 
# Iterate thru lines and extract x and y data 
for line in ax1.get_lines(): 
    xdata.append(line.get_xdata()) 
    ydata.append(line.get_ydata()) 

# New figure and plot the extracted data 
fig2 = plt.figure() 
ax2 = fig2.add_subplot(111) 
for X,Y in zip(xdata,ydata): 
    ax2.plot(X,Y) 

希望它有幫助。