【问题标题】:Python - Slider for X axis in MatplotlibPython - Matplotlib 中 X 轴的滑块
【发布时间】:2022-06-22 05:33:58
【问题描述】:

我正在使用 Python 进行数据分析。我的数据很大,绘制时看起来很乱。所以我尝试使用 X 轴滑块,以便用户可以在 x 轴上滑动并轻松地对其进行可视化。

我尝试了以下代码:

fig, ax1 = plt.subplots(figsize=(18,7))
plt.subplots_adjust(bottom=0.25)



Trial = ax1.plot(x,y,'.', color='blue',markersize=1,label='B1')

axpos = plt.axes([0.25, 0.05, 0.65, 0.03])
spos = Slider(axpos, 'Time', matplotlib.dates.date2num(2022,1,28), matplotlib.dates.date2num(2022,4,12))

def update(val):
    pos = spos.val
    ax1.axis([matplotlib.dates.date2num(pos), matplotlib.dates.date2num(pos)+relativedelta(months = 1),80,100])
    fig.canvas.draw_idle()

spos.on_changed(update)
plt.show()

我得到了如图所示的输出

我不知道我在做什么错误。我想要一个图,我想在一个月内有 X 轴,然后在下个月滑动它。例如,如果我的开始日期是 2022,1,28,我想一次查看到 2022,2,28,然后使用滑块查看下个月的日期。谁能帮帮我?

【问题讨论】:

    标签: python pandas dataframe slider


    【解决方案1】:

    在这里,但您必须用您的数据替换 x 和 y:

    import matplotlib.pyplot as plt
    import numpy as np
    import ipywidgets as wg
    
    @wg.interact(this=wg.FloatSlider(min=1, max=10, step=0.5, layout=wg.Layout(width="500px")))
    def run(this):
        
        fig, ax1 = plt.subplots(figsize=(8,4))
        plt.subplots_adjust(bottom=0.25)
    
        # x and y must be your data
        x= np.linspace(-5,5,1000) 
        y= np.sin(x)                       
    
        Trial = ax1.plot(x,y,'.', color='blue',markersize=1,label='B1')
    
        def update(val):
            pos = this
            ax1.axis([matplotlib.dates.date2num(pos), matplotlib.dates.date2num(pos)+relativedelta(months = 1),80,100])
    
        ax1.set_xlim(-this, this)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-26
      • 2020-07-08
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2021-04-03
      • 2017-10-19
      相关资源
      最近更新 更多