![](/img/trans.png)
[英]matplotlib combining subplots into a single plot with no axis and no gaps
[英]Converting several features of a single matplotlib plot into subplots
以下代碼段使我可以方便地繪制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 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個軸對象,然后遍歷它們(與DataFrames一起)並在loop內設置屬性。 以下是相關代碼
fig, axes = plt.subplots(3, 1, figsize=(8, 5), sharex=True)
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()
按自己的方式做
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.