简体   繁体   中英

Matplotlib - Formatting two plots on the same figure

I'm trying to plot some data but I'm getting stuck on plotting 2 plots on same figure. It looks like this:

在此处输入图片说明

The code is:

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()

How can I solve this questions:

1 - The plots looks like they are one above the other. How can I format this with a visual to look like independent plots on the same figure.

2 - I'm using this line of code to both plots "ax2.xaxis.set_major_formatter(DateFormatter('%d\\n%h\\n%Y'))" but there is no sync in the dates. The dates should be equal in the two plots.

Some one can give me a clue on this questions?

Best Regards,

You are not using add_subplot correctly:

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

The first number indicates the number of rows, the second the number of columns and the third the index of the plot.

If you want the plots to share the x axis (that is the axis with dates), you have to specify the sharex property.

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

You only have to set the major formatter once since they share the x axis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM