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

前端 未结 1 2009
刺人心
刺人心 2021-01-03 15:33

my task is simple: I have a time series ts (Euro Swiss Franc daily exchange rates between 2010 and 2014) to plot. In that plot I would like to highlight a certa

相关标签:
1条回答
  • 2021-01-03 16:25

    I have never used pandas, but I think that the problem is the range you are choosing for axins.set_xlim(x1, x2), they seem to be outside of the range. I just used the plotting capabilities of matplotlib and changed the range, and I obtained an image with the zoom.

    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

    0 讨论(0)
提交回复
热议问题