Python 将单个matplotlib绘图的多个要素转换为子绘图
下面的代码片段使我能够方便地绘制x轴日期时间数据帧:Python 将单个matplotlib绘图的多个要素转换为子绘图,python,matplotlib,Python,Matplotlib,下面的代码片段使我能够方便地绘制x轴日期时间数据帧: import pandas as pd import matplotlib matplotlib.use('QT5Agg') font = {'family': 'DejaVu Sans', # 'normal', 'size': 8} matplotlib.rc('font', **font) import matplotlib.pyplot as plt import matplotlib.dates as mdate
import pandas as pd
import matplotlib
matplotlib.use('QT5Agg')
font = {'family': 'DejaVu Sans', # 'normal',
'size': 8}
matplotlib.rc('font', **font)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def myMethod():
df1 = pd.DataFrame({"a": ["1989-12-31 23:59:12", "1999-12-31 23:59:13", "2009-12-31 23:59:14"], "b": [4, 5, 6]})
df1["date"] = pd.to_datetime(df1.a)
df1.set_index("date", inplace=True)
df1.drop(["a"], axis=1, inplace=True)
return df1
df1 = myMethod()
df2 = myMethod()
df3 = myMethod()
plt.rcParams["figure.dpi"] = 200
plt.xticks(rotation=20)
plt.grid()
plt.plot(df1, "-o", markersize=2)
plt.gca().fmt_xdata = lambda x: mdates.num2date(x).strftime("%Y-%m-%d %H:%M:%S")
plt.show()
yyyy-MM-dd hh:MM:ss
)的鼠标光标位置。请参阅本文末尾的屏幕截图df2
和df3
作为子地块。使用下面的代码可以做到这一点,但上面提到的功能将丢失。我必须如何更改代码才能为所有三个子地块实现这一点
ax1 = plt.subplot(3, 1, 1)
ax1.plot(df1)
ax2 = plt.subplot(3, 1, 2, sharex=ax1)
ax2.plot(df2)
ax3 = plt.subplot(3, 1, 3, sharex=ax1)
ax3.plot(df3)
plt.show()
通过在轴实例上循环并以面向对象的方式使用它们,可以直接在轴实例上工作。首先定义3轴对象,然后在其上循环(连同数据帧),并在循环内设置属性。以下是相关代码
按你的方式做
fig = plt.figure(figsize=(8, 5))
ax1 = plt.subplot(3, 1, 1)
ax2 = plt.subplot(3, 1, 2, sharex=ax1)
ax3 = plt.subplot(3, 1, 3, sharex=ax1)
axes = [ax1, ax2, ax3]
dfs = [df1, df2, df3]
for ax, df in zip(axes, dfs):
ax.plot(df1, "-o", markersize=8)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=20 )
ax.grid()
plt.gca().fmt_xdata = lambda x: mdates.num2date(x).strftime("%Y-%m-%d %H:%M:%S")
plt.tight_layout()
plt.show()
谢谢,这已经很酷很好了。很好!不幸的是,我确实错过了上部和中部子地块的完整
datetime
光标。目前,仅显示年份
。对于较低的一个,已显示完整的datetime
值。@user7468395:对于我来说,所有三个图中只显示年份,如图中所示。我的意思是鼠标悬停在左下角的x/y位置上。请参见编辑的文章和此屏幕截图:
fig = plt.figure(figsize=(8, 5))
ax1 = plt.subplot(3, 1, 1)
ax2 = plt.subplot(3, 1, 2, sharex=ax1)
ax3 = plt.subplot(3, 1, 3, sharex=ax1)
axes = [ax1, ax2, ax3]
dfs = [df1, df2, df3]
for ax, df in zip(axes, dfs):
ax.plot(df1, "-o", markersize=8)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=20 )
ax.grid()
plt.gca().fmt_xdata = lambda x: mdates.num2date(x).strftime("%Y-%m-%d %H:%M:%S")
plt.tight_layout()
plt.show()