在matplotlib子图的主图侧面添加两个较小的子图 [英] Adding two smaller subplots to the side of my main plot in matplotlib subplots
问题描述
目前,我的图表仅在左侧显示主要的大图表.
Currently my chart is showing only the main big chart on the left.
但是,我现在想在主图的右侧添加两个较小的图;每个单独的数据集.
However, I now want to add the two smaller plots to the right-hand side of my main plot; with each individual set of data.
我正在努力研究子图以弄清楚如何做到这一点.我下面的照片显示了我想要的输出.
I am struggling with subplots to figure out how to do this. My photo below shows my desired output.
filenamesK = glob("C:/Users/Ke*.csv")
filenamesZ = glob("C:/Users/Ze*.csv")
K_Z_Averages = {'K':[], 'Z':[]}
# We will create a function for plotting, instead of nesting lots of if statements within a long for-loop.
def plot_data(filename, fig_ax, color):
df = pd.read_csv(f, sep=',',skiprows=24) # Read in the csv.
df.columns=['sample','Time','ms','Temp1'] # Set the column names
df=df.astype(str) # Set the data type as a string.
df["Temp1"] = df["Temp1"].str.replace('\+ ', '').str.replace(' ', '').astype(float) # Convert to float
# Take the average of the data from the Temp1 column, starting from sample 60 until sample 150.
avg_Temp1 = df.iloc[60-1:150+1]["Temp1"].mean()
# Append this average to a K_Z_Averages, containing a column for average from each K file and the average from each Z file.
# Glob returns the whole path, so you need to replace 0 for 10.
K_Z_Averages[os.path.basename(filename)[0]].append(avg_Temp1)
fig_ax.plot(df[["Temp1"]], color=color)
fig, ax = plt.subplots(figsize=(20, 15))
for f in filenamesK:
plot_data(f, ax, 'blue')
for f in filenamesZ:
plot_data(f, ax, 'red')
plt.show()
推荐答案
@max 的回答很好,但你也可以做 matplotlib>=3.3 的是
@max 's answer is fine, but something you can also do matplotlib>=3.3 is
import matplotlib.pyplot as plt
fig = plt.figure(constrained_layout=True)
axs = fig.subplot_mosaic([['Left', 'TopRight'],['Left', 'BottomRight']],
gridspec_kw={'width_ratios':[2, 1]})
axs['Left'].set_title('Plot on Left')
axs['TopRight'].set_title('Plot Top Right')
axs['BottomRight'].set_title('Plot Bottom Right')
请注意,重复使用名称'Left'
两次表示该子图在布局中占据了两个位置.还要注意 width_ratios
的使用.
Note hw the repeated name 'Left'
is used twice to indicate that this subplot takes up two slots in the layout. Also note the use of width_ratios
.
这篇关于在matplotlib子图的主图侧面添加两个较小的子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!