1

我正在尝试绘制一些数据,但我被困在同一个图上绘制 2 个图。它看起来像这样:

在此处输入图像描述

代码是:

import re
import sqlite3
import matplotlib.pyplot as plt
from matplotlib.dates import datetime as dt
from matplotlib.dates import DateFormatter

...

for company in companies:
    cursor.execute("select distinct url from t_surv_data where company = ? order by product_type", (company,))
    urls = [r[0] for r in cursor.fetchall()]

    for idx, url in enumerate(urls):              
    cursor.execute("select price, timestamp from t_surv_data where url = ? order by timestamp", (url,))
    data = [[r[0], r[1]] for r in cursor.fetchall()]
    price, date = zip(*data)                
    date = [dt.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in date]

    f = plt.figure('''figsize=(3, 2)''')

    ax = f.add_subplot(111)
    ax.plot(date, price) # x, y
    ax.xaxis.set_major_formatter(DateFormatter('%d\n%h\n%Y'))
    #ax.set_ylim(ymin=0) # If I use this a break the plot

    ax2 = f.add_subplot(211)
    ax2.scatter(date, [1,1,-1])
    ax2.xaxis.set_major_formatter(DateFormatter('%d\n%h\n%Y'))
    #ax2.set_ylim(ymin=-1, ymax=1) # If I use this a break the plot

    plt.savefig('plt/foo' + str(idx) + '.png')
    plt.close()

我该如何解决这个问题:

1 - 地块看起来像是一个在另一个之上。我怎样才能用视觉来格式化它,让它看起来像同一个图上的独立图。

2 - 我使用这行代码来绘制“ax2.xaxis.set_major_formatter(DateFormatter('%d\n%h\n%Y'))”,但日期没有同步。两个图中的日期应该相等。

有人可以给我这个问题的线索吗?

此致,

4

2 回答 2

3

您没有add_subplot正确使用:

ax = f.add_subplot(2,1,1)
ax2 = f.add_subplot(2,1,2)

第一个数字表示行数,第二个数字表示列数,第三个数字表示绘图的索引。

于 2013-08-30T18:41:26.297 回答
2

如果您希望绘图共享 x 轴(即带有日期的轴),则必须指定sharex属性。

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(...)
ax2.scatter(...)
ax1.xaxis.set_major_formatter(DateFormatter('%d\n%h\n%Y'))

您只需设置一次主要格式化程序,因为它们共享 x 轴。

于 2013-08-30T18:45:02.630 回答