我有两个时间序列数据y en y1。问题在于y的范围是400到600,而y1的范围是9到18,因此在进行绘制时,我无法进行很好的比较。我想知道是否有一种技术可以在不更改y1值(例如y1 ** 2)的情况下将图表缩放到时间序列。 代码:
y = pd.Series(np.random.randint(400, high=600, size=255))
y1 = pd.Series(np.random.randint(9, high=18, size=255))
date_today = datetime.now()
x = pd.date_range(date_today, date_today + timedelta(254), freq='D')
plt.plot(x,y,color = 'r',\
label = 'Stock',linewidth = 2)
plt.plot(x,y1,color = 'k',\
label = 'Index',linewidth = 2)
plt.title('Stock versus Index', fontsize=24,fontweight='bold')
plt.grid(linewidth=1.5)
输出:
答案 0 :(得分:1)
基于pylab
(here)的官方示例,我为您创建了一个可行的解决方案,如下所示:
from datetime import datetime
from datetime import timedelta
import pandas as pd
f, (ax, ax2) = plt.subplots(2, 1, sharex=True, figsize=(8, 6))
y = pd.Series(np.random.randint(400, high=600, size=255))
y1 = pd.Series(np.random.randint(9, high=18, size=255))
date_today = datetime.now()
x = pd.date_range(date_today, date_today + timedelta(254), freq='D')
ax.plot(x,y,color = 'r',label = 'Stock',linewidth = 2)
ax.plot(x,y1,color = 'k',label = 'Index',linewidth = 2)
ax2.plot(x,y,color = 'r',label = 'Stock',linewidth = 2)
ax2.plot(x,y1,color = 'k',label = 'Index',linewidth = 2)
ax.set_title('Stock versus Index', fontsize=24,fontweight='bold')
ax.grid(linewidth=1.5)
ax2.grid(linewidth=1.5)
ax.set_ylim(400, 620) # upper data
ax2.set_ylim(5, 20) # lower data
# Merging and removing the middle horizontal axes
ax.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax.xaxis.tick_top()
ax.tick_params(labeltop='off')
ax2.xaxis.tick_bottom()
# Modifying aesthetics of diagonal splitting lines
d = .01
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((-d, +d), (-d, +d), **kwargs)
ax.plot((1 - d, 1 + d), (-d, +d), **kwargs)
kwargs.update(transform=ax2.transAxes)
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs)
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs)
输出
答案 1 :(得分:1)
您可以使用两个刻度。
这是您的代码,由于我不熟悉而进行了更改以避免熊猫:
import numpy as np
import matplotlib.pyplot as plt
from datetime import *
#y = pd.Series(np.random.randint(400, high=600, size=255))
y = np.random.randint(400, high=600, size=255)
#y1 = pd.Series(np.random.randint(9, high=18, size=255))
y1 = np.random.randint(9, high=18, size=255)
date_today = datetime.now()
#x = pd.date_range(date_today, date_today + timedelta(254), freq='D')
x = [date_today + timedelta(days=x) for x in range(0, 255)]
fig, ax1 = plt.subplots()
ax1.plot(x,y,color = 'r',\
label = 'Stock',linewidth = 2)
ax1.set_ylabel('Stock', color='r')
ax1.tick_params('y', colors='r')
ax2 = ax1.twinx()
ax2.plot(x,y1,color = 'k',\
label = 'Index',linewidth = 2)
ax2.set_ylabel('Index', color='k')
ax2.tick_params('y', colors='k')
plt.title('Stock versus Index', fontsize=24,fontweight='bold')
plt.grid(linewidth=1.5)
plt.show()
作为参考,请检查:two_scales.py