[英]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;但是,我现在想将两个较小的图添加到主 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.
下面的照片显示了我想要的 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 's answer is fine, but something you can also do matplotlib>=3.3 is @max 的答案很好,但你也可以做 matplotlib>=3.3 是
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')
Note hw the repeated name 'Left'
is used twice to indicate that this subplot takes up two slots in the layout.请注意,重复的名称
'Left'
被使用了两次,表示该子图在布局中占据了两个位置。 Also note the use of width_ratios
.还要注意
width_ratios
的使用。
This is a tricky question.这是一个棘手的问题。 Essentially, you can place a grid on a figure (
add_gridspec()
) and than open subplots ( add_subplot()
) in and over different grid elements.本质上,您可以在图形上放置一个网格 (
add_gridspec()
add_subplot()
),然后在不同的网格元素中打开子图 ( add_subplot() )。
import matplotlib.pyplot as plt
# open figure
fig = plt.figure()
# add grid specifications
gs = fig.add_gridspec(2, 3)
# open axes/subplots
axs = []
axs.append( fig.add_subplot(gs[:,0:2]) ) # large subplot (2 rows, 2 columns)
axs.append( fig.add_subplot(gs[0,2]) ) # small subplot (1st row, 3rd column)
axs.append( fig.add_subplot(gs[1,2]) ) # small subplot (2nd row, 3rd column)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.