Skip to main content
 首页 » 编程设计

python之如何调整和塑造子图

2024年09月07日10over140

我正在尝试在一个图中绘制 2 个图。所以只需 2 个子图并调整图形大小并找到一个像样的。目前我正在使用这段代码:

import matplotlib.pyplot as plt 
import pandas as pd 
#import numpy as np     
 
#####  import data ##### 
 
df=pd.read_csv('C:\\Users\Kevin\Documents\Afstudeer\Measurements/1st_plot.txt',sep=',',decimal='.',header=None) 
df.columns=['Vx','Vy','undefined','Laser_signal'] 
 
fig, ax = plt.subplots(figsize=(8, 5))  
ax1=fig.add_subplot(121) 
 
ax1.plot(df['Vx'],df['Vy'],label='plot') 
plt.xlabel(r'$V_x$') 
plt.ylabel(r'$V_y$') 
 
ax2=fig.add_subplot(122) 
 
ax1.scatter(df['Vx'],df['Vy'],label='data_points') 
plt.xlabel(r'$V_x$') 
plt.ylabel(r'$V_y$') 
 
plt.subplots_adjust(left=.2, bottom=.45, right=.8, top=.95, 
                wspace=.3, hspace=.4) 

所以这是最后一段代码让我感到困惑。当我做这个情节时,我得到这样的东西:

这是我的示例数据:

-1.725953467,0.109343505,-10.433363664,0.159675246 
-1.725953467,0.110607445,-10.433363664,0.159675246 
-1.729140157,0.110607445,-10.433363664,0.159675246 
-1.722766777,0.10839555,-10.433363664,0.159675246 
-1.727865481,0.11534722,-10.433363664,0.159359499 
-1.726272136,0.112503355,-10.433363664,0.159675246 
-1.731689509,0.120086995,-10.433363664,0.159359499 
-1.727228143,0.117559115,-10.433363664,0.159359499 
-1.729140157,0.11977101,-10.433363664,0.159675246 
-1.730096164,0.121350935,-10.433363664,0.159675246 
-1.729458826,0.122614875,-10.433363664,0.159043752 
-1.735832206,0.12482677,-10.433363664,0.159359499 
-1.728821488,0.121350935,-10.433363664,0.159675246 
-1.733920192,0.124510785,-10.433363664,0.159359499 
-1.731052171,0.12166692,-10.433363664,0.159675246 
-1.739018896,0.12735465,-10.433363664,0.159043752 
-1.738062889,0.12861859,-10.433363664,0.159043752 
-1.738700227,0.133358365,-10.433363664,0.159043752 
-1.73455753,0.12988253,-10.433363664,0.159043752 
-1.743161593,0.144101855,-10.433363664,0.159043752 

正如您将从代码中看到的那样,我只取前两列。我期待一个图中有 2 个子图。那么,为什么我要在地 block 之间得到这些上行和下行??

请您参考如下方法:

两条线

fig, ax = plt.subplots(figsize=(8, 5))  
ax1=fig.add_subplot(121) 

在某种程度上是相互排斥的。您可以通过

创建子图
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 5))  

或者您通过

创建它们
fig = plt.figure() 
ax1=fig.add_subplot(121) 
ax2=fig.add_subplot(122) 

之后最好使用轴句柄 ax1 和 ax2 来设置任何属性,例如

ax1.set_xlabel(r'$V_x$') 

代替 plt.xlabel。