2015-05-06 30 views
1

我知道有多种方法可以在一个图中绘制多个图形。一种这样的方式是使用轴,例如,如何绘制小图中的图形(Matplotlib)

import matplotlib.pyplot as plt 
fig, ax = plt.subplots() 
ax.plot([range(8)]) 
ax.plot(...) 

因为我有我的美化图表和随后返回一个数字的功能,我想用这个数字在我的次要情节来绘制。它应该看起来类似于此:

import matplotlib.pyplot as plt 
fig, ax = plt.subplots() 
ax.plot(figure1) # where figure is a plt.figure object 
ax.plot(figure2) 

这不起作用,但我怎么能使它工作?有没有办法将数字放在子图或者解决方法中,在一个整体数字中绘制多个数字?

任何帮助,这是非常感谢。 在此先感谢您的意见。

回答

1

一种可能的解决方案是

import matplotlib.pyplot as plt 

# Create two subplots horizontally aligned (one row, two columns) 
fig, ax = plt.subplots(1,2) 
# Note that ax is now an array consisting of the individual axis 

ax[0].plot(data1) 
ax[1].plot(data2) 

然而,为了工作data1,2需要是数据。如果你有一个已经为你绘制数据的函数,我建议在你的函数中包含axis参数。例如

def my_plot(data,ax=None): 
    if ax == None: 
     # your previous code 
    else: 
     # your modified code which plots directly to the axis 
     # for example: ax.plot(data) 

然后你就可以绘制它像

import matplotlib.pyplot as plt 

# Create two subplots horizontally aligned 
fig, ax = plt.subplots(2) 
# Note that ax is now an array consisting of the individual axis 

my_plot(data1,ax=ax[0]) 
my_plot(data2,ax=ax[1]) 
+0

非常感谢您的回答,但这正是我想要规避的。我不想绘制数据,而是一个容易检索的图形对象。 – Arne

+1

@Arne:我从来没有见过内置函数,其中包含两个数字成一个单一的数字。因此,有必要从数字对象中提取所有数据,并使用多个坐标轴在新图中再次绘制它们。尽管这可能是可能的,但比简单地将轴作为参数更复杂。 – plonser

1

如果目标仅仅是定制个人次要情节,为什么不改变你的函数动态更改目前的数字,而不是返回一个数字。从matplotlibseaborn,你可以改变绘图时的绘图设置吗?

import numpy as np 
import matplotlib.pyplot as plt 

plt.figure() 

x1 = np.linspace(0.0, 5.0) 
x2 = np.linspace(0.0, 2.0) 

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) 
y2 = np.cos(2 * np.pi * x2) 

plt.subplot(2, 1, 1) 
plt.plot(x1, y1, 'ko-') 
plt.title('A tale of 2 subplots') 
plt.ylabel('Damped oscillation') 

import seaborn as sns 

plt.subplot(2, 1, 2) 
plt.plot(x2, y2, 'r.-') 
plt.xlabel('time (s)') 
plt.ylabel('Undamped') 

plt.show() 

enter image description here

也许我并不完全明白你的问题。这个“美化”功能是否复杂?...

相关问题