Interactive Plots in Python

Question:

How to plot interactive plots in python, I am on dataframe which is datetime indexed, I want to plot multiple columns by selecting from the wizard, on the time axis, there should be some function to behave like a date slider as well so that selecting a range in the plot can change the date.
Any suggestion?

I have no idea about the interactive plots, being new to python I can just plot pd or matplotlib plot as basic

Asked By: manish maurya

||

Answers:

  • My choice is Plotly
import plotly.express as px
import plotly.graph_objects as go

fig = px.line(x=x, y=y)

fig.update_layout(xaxis=dict(rangeslider=dict(visible=True)))

fig.show()
  • On the other hand it could be Bokeh
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, DateRangeSlider

p = figure(plot_width=400, plot_height=400)
p.line(x, y)

source = ColumnDataSource(data=dict(x=x, y=y))
date_range_slider = DateRangeSlider(start=min(x), end=max(x), value=(min(x), max(x)), step=1)

def update_plot(attr, old, new):
    x_range = date_range_slider.value
    source.data = source.data[source.data['x'].between(*x_range)]

date_range_slider.on_change("value", update_plot)

layout = column(p, date_range_slider)
show(layout)
  • So if Matplotlib is more comfortable for you here is example for it
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

fig, ax = plt.subplots()
line, = ax.plot(x, y)

date_range_slider = Slider(ax, 'Date Range', min(x), max(x), valinit=min(x), valfmt='%d-%m-%Y')

def update_plot(val):
    x_range = date_range_slider.val
    line.set_xdata(x[x>=x_range[0]])
    line.set_ydata(y[x>=x_range[0]])
    fig.canvas.draw_idle()

date_range_slider.on_changed(update_plot)

plt.show()
Answered By: di.bezrukov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.