python - 如何使用 matplotlib 在子图中调整图形大小

标签 python matplotlib pandas subplot

我正在尝试调整子图中两个图形的大小。基本上,我想要一个温度曲线为 111 且压力曲线为 211 的子图。但是,我希望压力图小于温度图。如果没有相当复杂的 gridspec 库,这可能吗?我有以下代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# ------Pressure------#

df1 = pd.DataFrame.from_csv('Pressure1.csv',index_col = None)
df1['P'] = df1['P'].str.split('.').str[:-1].str.join(',').str.replace(',', '.').astype(np.float64)
a = df1['T']
a /= 2900 # Convert milliseconds to hours
initial_time = 0
a += initial_time - min(a)
b = df1['P']
b -=+1 #convert from volts to bar

# ------- Temperature----------#

df = pd.DataFrame.from_csv('Temperature1.csv',index_col = None)

w = df['Time']
w /= 3600000 # Convert milliseconds to hours
initial_time = 0
w += initial_time - min(w)

x = df['Input 1']
y = df['Input 2']
z = df['Input 3']

#----subplot----#

plt.subplot(1,1,1)
figsize(20,10)
plt.plot(w,x, label = "Top_sensor")
plt.plot(w,y, label = "Mid_sensor")
plt.plot(w,z, label = 'Bot_sensor')
plt.title('Temperature')
plt.xlabel('Time(Hours)')
plt.ylabel('Temperature (K)')
plt.ylim(70, 200)
plt.xlim(0, 12, 1)
plt.show()

plt.subplot(2,1,1)
figsize(20,3)
plt.plot(a,b)
plt.title('Pressure_Monitoring')
plt.xlabel('Time(Hours)')
plt.ylabel('Pressure (Bar)')
plt.xlim(0, 12, 1)
plt.show()

看看我如何尝试更改每个子图中的图形大小。这是错误的方法吗?

好的,所以我已经设法获得了我想要的 gridspec。但是,我如何将两者结合起来?

import matplotlib.gridspec as gridspec

f = plt.figure()

gs = gridspec.GridSpec(2, 1,width_ratios=[20,10], height_ratios=[10,5])

ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

plt.show()

最佳答案

这就是 pyplot 界面如此糟糕的原因。这比它需要的要复杂得多。

加载并准备您的数据。然后:

fig = plt.Figure(figsize=(20, 3))
gs = gridspec.GridSpec(2, 1, width_ratios=[20,10], height_ratios=[10,5])
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])

ax1.plot(...)
ax1.set_ylabel(...)
...

ax2.plot(...)
ax2.set_xlabel(...)

这样一来,您就不必创建任何不真正使用的无关对象,并且始终明确指出要修改的轴。

关于python - 如何使用 matplotlib 在子图中调整图形大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28279430/

相关文章:

python - 减小盒子尺寸

python - 带有词袋的文本分类器和 sklearn 中的附加情感特征

python - Pandas - 高效的元素比较

python - 散点图颜色条 - Matplotlib

python - 将列合并为一列

python - 按元组列表过滤 DataFrame 的行

python - Seaborn FacetGrid 堆叠条形图

python - 快速 Python 绘图库直接在 2D numpy 数组图像缓冲区上绘制绘图?

python - 如何用 Python cartopy 给一个国家贴上标签?

python - Pandas 线性插值按另一列分组