[英]Matplotlib - Formatting two plots on the same figure
我正在嘗試繪制一些數據,但在同一圖上繪制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'))”,但日期中沒有同步。 在兩個圖中,日期應該相等。
有人可以給我一個有關這個問題的線索嗎?
最好的祝福,
您沒有正確使用add_subplot
:
ax = f.add_subplot(2,1,1)
ax2 = f.add_subplot(2,1,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軸。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.