gpt4 book ai didi

python - Matplotlib/ Pandas : Zoom Part of a Plot with Time Series

转载 作者:行者123 更新时间:2023-11-28 22:47:27 33 4
gpt4 key购买 nike

我的任务很简单:我有一个时间序列 ts(2010 年至 2014 年间欧元瑞士法郎的每日汇率)要绘制。在该图中,我想通过放大来突出显示某个时间间隔。然而,缩放后的窗口仍然是空的(见下面的代码)。此外,我在选择放大窗口的 x 范围时遇到问题,因为我不知道如何将日期正确转换为 matplotlib 的内部整数表示。

在此先感谢您的帮助!

这是我的代码:

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# Load the time series
ts = pd.read_csv('./Data/EUR_CHF_Exchange_Rates/EUR_CHF_daily.csv',sep=';', parse_dates=['time'], index_col = 'time',decimal=',')
ts = ts['EUR/CHF']
ts = ts.sort_index(ascending=True)

# Plot
fig = plt.figure(figsize=(14,5))
ax = plt.axes()
ts.plot() # ts is my time series

# Label the axis
ax.set_xlabel('')
ax.set_ylabel('EUR/CHF')

#I want to select the x-range for the zoomed region. I have figured it out suitable values
# by trial and error. How can I pass more elegantly the dates as something like
# x1 = '2012-05-09'
# x2 = '2012-09-02'
x1 = 15439.0
x2 = 15588.0

# select y-range for zoomed region
y1 = 1.15
y2 = 1.25

# Make the zoom-in plot:
axins = zoomed_inset_axes(ax, 2, loc=1) # zoom = 2
axins.plot(ts)
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.savefig('daily_exchange_rates.pdf') # The zoomed window is empty!!!!

最佳答案

我从未使用过pandas,但我认为问题在于您为axins.set_xlim(x1, x2) 选择的范围,它们似乎在外部的范围。我只是使用了 matplotlib 的绘图功能并更改了范围,并获得了缩放后的图像。

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# Load the time series
ts = pd.read_csv('EUR_CHF_daily.csv',sep=';', parse_dates=['time'], index_col = 'time',decimal=',')
ts = ts['EUR/CHF']
ts = ts.sort_index(ascending=True)

# Plot
fig = plt.figure(figsize=(14,5))
ax = plt.axes()
ax.plot(ts)

# Label the axis
ax.set_xlabel('')
ax.set_ylabel('EUR/CHF')

#I want to select the x-range for the zoomed region. I have figured it out suitable values
# by trial and error. How can I pass more elegantly the dates as something like
x1 = 1543.90
x2 = 1658.80

# select y-range for zoomed region
y1 = 1.15
y2 = 1.25

# Make the zoom-in plot:
axins = zoomed_inset_axes(ax, 2, loc=1) # zoom = 2
axins.plot(ts)
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()

enter image description here

关于python - Matplotlib/ Pandas : Zoom Part of a Plot with Time Series,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26223937/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com