Python Jupyter-使用相同的x轴合并2个绘图

Python Jupyter-使用相同的x轴合并2个绘图,python,matplotlib,plot,jupyter-notebook,Python,Matplotlib,Plot,Jupyter Notebook,我已经从Jupyter使用matplotlib生成了以下绘图。 两个图具有相同的x轴,因此我希望合并它们,即两个图具有一个公共的x轴 这是我使用的代码。如何将结果集成到此代码中 import numpy as np import pandas as pd from scipy.optimize import curve_fit import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator f

我已经从Jupyter使用matplotlib生成了以下绘图。 两个图具有相同的x轴,因此我希望合并它们,即两个图具有一个公共的x轴

这是我使用的代码。如何将结果集成到此代码中

import numpy as np 
import pandas as pd
from scipy.optimize import curve_fit    
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

file1 = '1.dat'
file2 = '1SED.dat'

data1 = pd.read_csv(file1, delimiter='\s+', header=None, engine='python')
data1.columns = ['Wavelength','Obs.Flux','Obs.Error','Flux','Error','FluxMod','Fitted','Excess','(F-Fm)']

data2 = pd.read_csv(file2, delimiter='\s+', header=None, engine='python')
data2.columns = ['wave','cflux']


def fit_data():

fig = plt.figure(1,figsize=(10,9))

plt.subplot(211)
np.linspace(1000,3E4)
plt.plot(data2['wave'], data2['cflux'],   color='cornflowerblue', linestyle= '-', lw=0.5)
plt.scatter(data1['Wavelength'], data1['Obs.Flux'],  marker='o', color='red', s=75)

#plt.xlabel('$\lambda (\AA)$',size=15)
plt.ylabel('$F_{\lambda} (erg/cm^{2}/s/\AA)$',size=15)
plt.yscale('log')
plt.xscale('log')
plt.ylim(1E-18,4E-17)
plt.xlim(1000,2E4)
plt.title('Star No. 1')

plt.subplot(212)
plt.plot(data1['Wavelength'], data1['(F-Fm)'],  marker='o', color='red')
plt.plot(data1['Wavelength'], data1['(F-Fm)'],  linestyle='-', color='red', lw=1.5)
plt.xlabel('$\lambda (\AA)$',size=15)
plt.xscale('log')

plt.savefig("1SED")

plt.show()
plt.close()

fit_data()
我尝试使用您建议的编辑,但收到以下错误

TypeError                                 Traceback (most recent call last)
<ipython-input-8-d43e496e030f> in <module>()
     32     plt.close()
     33 
---> 34 fit_data()


<ipython-input-8-d43e496e030f> in fit_data()
     16 #... other commands to be applied on ax1
     17 
---> 18     ax2 = fig.add_subplot(212, sharex=True)
     19     ax2.plot(data1['Wavelength'], data1['(F-Fm)'],  marker='o', color='red')
     20     ax2.plot(data1['Wavelength'], data1['(F-Fm)'],  linestyle='-', color='red', lw=1.5)

~/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py in add_subplot(self, *args, **kwargs)
   1072                     self._axstack.remove(ax)
   1073 
-> 1074             a = subplot_class_factory(projection_class)(self, *args, **kwargs)
   1075 
   1076         self._axstack.add(key, a)

~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_subplots.py in __init__(self, fig, *args, **kwargs)
     71 
     72         # _axes_class is set in the subplot_class_factory
---> 73         self._axes_class.__init__(self, fig, self.figbox, **kwargs)
     74 
     75     def __reduce__(self):

~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py in __init__(self, fig, rect, facecolor, frameon, sharex, sharey, label, xscale, yscale, axisbg, **kwargs)
    496         self._sharey = sharey
    497         if sharex is not None:
--> 498             self._shared_x_axes.join(self, sharex)
    499             if sharex._adjustable == 'box':
    500                 sharex._adjustable = 'datalim'

~/anaconda3/lib/python3.6/site-packages/matplotlib/cbook/__init__.py in join(self, a, *args)
   1493 
   1494         for arg in args:
-> 1495             set_b = mapping.get(ref(arg))
   1496             if set_b is None:
   1497                 set_a.append(ref(arg))

TypeError: cannot create weak reference to 'bool' object
TypeError回溯(最近一次调用)
在()
32 plt.close()
33
--->34拟合数据()
in fit_data()
16 #... 要应用于ax1的其他命令
17
--->18 ax2=图add_子批次(212,sharex=True)
19 ax2.绘图(数据1['波长'],数据1['(F-Fm)”,标记为'o',颜色为红色')
20 ax2.绘图(数据1['波长'],数据1['(F-Fm)”,线型='-',颜色='红色',lw=1.5)
在add_子包(self,*args,**kwargs)中的~/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py
1072自卸除(ax)
1073
->1074 a=子地块等级工厂(投影等级)(自,*args,**kwargs)
1075
1076自.\u axstack.add(键,a)
~/anaconda3/lib/python3.6/site-packages/matplotlib/axes//u subplots.py in\uuuu\u init\uuuu(self,图,*args,**kwargs)
71
72##(U轴)(U类)在子批次(U类)工厂中设置
--->73 self.\u axes\u class.\uuuuuu init\uuuuu(self,fig,self.figbox,**kwargs)
74
75定义减少(自):
~/anaconda3/lib/python3.6/site-packages/matplotlib/axes//u base.py in_uuu_uinit_uuu(self、fig、rect、facecolor、frameon、sharex、sharey、label、xscale、yscale、axisbg、**kwargs)
496 self.\u sharey=sharey
497如果sharex不是无:
-->498自共享x轴连接(自共享)
499如果sharex.\u可调=='box':
500 sharex.\u可调='datalim'
~/anaconda3/lib/python3.6/site packages/matplotlib/cbook/\uu init\uuuu.py加入(self,a,*args)
1493
1494对于args中的arg:
->1495 set_b=mapping.get(参考(arg))
1496如果设置为“无”:
1497集合附加(参考(参数))
TypeError:无法创建对“bool”对象的弱引用

要个性化这样的子绘图,matplotlib的面向对象API使代码更加简单

您已经有了
fig=plt.figure(…
),那么您需要执行
ax1=fig.add_子图(211)
,并修改大多数调用的方法,一般来说,在名称(即xlabel、yscale、title…)前面添加一个
set
,如果有疑问,请咨询

此外,我评论的其他链接中的答案也可以使用。与上述代码的主要区别在于使用
sharex=True
强制两个子地块具有相同的X轴,并且在绘制后,使用
setp
subplot\u adjust
删除标签和空格

因此,代码如下所示:

fig = plt.figure(1,figsize=(10,9))

ax1= fig.add_subplot(211)
ax1.plot(data2['wave'], data2['cflux'],   color='cornflowerblue', linestyle= '-', lw=0.5)
ax1.scatter(data1['Wavelength'], data1['Obs.Flux'],  marker='o', color='red', s=75)

ax1.set_ylabel('$F_{\lambda} (erg/cm^{2}/s/\AA)$',size=15)
ax1.set_yscale('log')
#... other commands to be applied on ax1

ax2 = fig.add_subplot(212, sharex=ax1)
#... other commands to be applied on ax2

plt.setp(ax1.get_xticklabels(), visible=False) # hide labels
fig.subplots_adjust(hspace=0) # remove vertical space between subplots

可能重复的否,我想要下一个图形的顶部(边框)和第一个图形的底部(边框)坐在一起。我可以在Windows的Origin上这样做。但是想在这里做同样的事情,你必须将上面的答案与这个答案结合起来,或者直接看看这个matplotlib示例。我编辑了这个问题并添加了我的代码。你能帮我吗?我试过代码,它编译并打印出第一个绘图,但不打印第二个绘图d、 我已将错误包括在原件中question@Bryan哦,抱歉,我不知道为什么我写的是True。我已经更正了它。它应该是ax1,以便告诉matplotlib xaxis应该与谁共享。我试图通过删除该语句来编译它,但它成功了。我还有一个问题。我需要在第一个绘图中添加错误栏。使用TOPCAT这样做很容易。我尝试使用matplotlib页面的帮助,但它以错误终止。知道如何修复它吗?然后只需执行
ax1.errorbar()
而不是
ax1.scatter
ax1.plot
。以下是errorbar方法的文档: