Update graph/plot with fixed interval of time
As an example you can run the following locally:
library(shiny)
runApp(list(
ui = pageWithSidebar(
headerPanel("Hello Shiny!"),
sidebarPanel(
sliderInput("obs",
"Number of observations:",
min = 1,
max = 1000,
value = 500)
),
mainPanel(
plotOutput("distPlot")
)
),
server =function(input, output, session) {
autoInvalidate <- reactiveTimer(5000, session)
output$distPlot <- renderPlot({
autoInvalidate()
# generate an rnorm distribution and plot it
dist <- rnorm(input$obs)
hist(dist)
})
}
))
A different normal sample will be generated every 5 seconds
Updating Graph on Interval on React
You could just add a setInterval in your useEffect to grab the data and update them again. Don't forgot to clear the interval on return:
useEffect(() => {
const interval = setInterval(() => asyncFetch(), 5000)
return () => clearInterval(interval)
}, []}
This example triggers every 5000ms, change the value according to your needs.
How do I plot in real-time in a while loop using matplotlib?
Here's the working version of the code in question (requires at least version Matplotlib 1.1.0 from 2011-11-14):
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0, 10, 0, 1])
for i in range(10):
y = np.random.random()
plt.scatter(i, y)
plt.pause(0.05)
plt.show()
Note the call to plt.pause(0.05)
, which both draws the new data and runs the GUI's event loop (allowing for mouse interaction).
Google Visualization Line Chart with fixed interval
In addition to sorting your data, it sounds like you want to use the timeofday type of value, documented minimally at: https://google-developers.appspot.com/chart/interactive/docs/reference?hl=en#DataTable_getValue
You should be able to use values like this:
data.addColumn('timeofday', 'Time');
data.addColumn('number', 'Leads');
data.addRow([[0, 0, 0, 1377011402000],5]);
data.addRow([[0, 0, 0, 1376967661000],12]);
How to plot multiple daily time series, aligned at specified trigger times?
Assuming the index has already been converted to_datetime
, create an IntervalArray
from -2H to +8H of the index:
dl, dr = -2, 8
left = df.index + pd.Timedelta(f'{dl}H')
right = df.index + pd.Timedelta(f'{dr}H')
df['interval'] = pd.arrays.IntervalArray.from_arrays(left, right)
Then for each ANNOUNCEMENT
, plot the window from interval.left
to interval.right
:
- Set the x-axis as seconds since
ANNOUNCEMENT
- Set the labels as hours since
ANNOUNCEMENT
fig, ax = plt.subplots()
for ann in df.loc[df['msg_type'] == 'ANNOUNCEMENT'].itertuples():
window = df.loc[ann.interval.left:ann.interval.right] # extract interval.left to interval.right
window.index -= ann.Index # compute time since announcement
window.index = window.index.total_seconds() # convert to seconds since announcement
window.plot(ax=ax, y='value', label=ann.Index.date())
deltas = np.arange(dl, dr + 1)
ax.set(xticks=deltas * 3600, xticklabels=deltas) # set tick labels to hours since announcement
ax.legend()
Here is the output with a smaller window -1H to +2H just so we can see the small sample data more clearly (full code below):
Full code:
import io
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
s = '''
date,value,msg_type
2022-03-15 08:15:10+00:00,122,None
2022-03-15 08:25:10+00:00,125,None
2022-03-15 08:30:10+00:00,126,None
2022-03-15 08:30:26.542134+00:00,127,ANNOUNCEMENT
2022-03-15 08:35:10+00:00,128,None
2022-03-15 08:40:10+00:00,122,None
2022-03-15 08:45:09+00:00,127,None
2022-03-15 08:50:09+00:00,133,None
2022-03-15 08:55:09+00:00,134,None
2022-03-16 09:30:09+00:00,132,None
2022-03-16 09:30:13.234425+00:00,135,ANNOUNCEMENT
2022-03-16 09:35:09+00:00,130,None
2022-03-16 09:40:09+00:00,134,None
2022-03-16 09:45:09+00:00,135,None
2022-03-16 09:50:09+00:00,134,None
'''
df = pd.read_csv(io.StringIO(s), index_col=0, parse_dates=['date'])
# create intervals from -1H to +2H of the index
dl, dr = -1, 2
left = df.index + pd.Timedelta(f'{dl}H')
right = df.index + pd.Timedelta(f'{dr}H')
df['interval'] = pd.arrays.IntervalArray.from_arrays(left, right)
# plot each announcement's interval.left to interval.right
fig, ax = plt.subplots()
for ann in df.loc[df['msg_type'] == 'ANNOUNCEMENT')].itertuples():
window = df.loc[ann.interval.left:ann.interval.right] # extract interval.left to interval.right
window.index -= ann.Index # compute time since announcement
window.index = window.index.total_seconds() # convert to seconds since announcement
window.plot(ax=ax, y='value', label=ann.Index.date())
deltas = np.arange(dl, dr + 1)
ax.set(xticks=deltas * 3600, xticklabels=deltas) # set tick labels to hours since announcement
ax.grid()
ax.legend()
Related Topics
How to Count How Many Values Per Level in a Given Factor
Plotting Cumulative Counts in Ggplot2
Error in Eval(Expr, Envir, Enclos):Object Not Found
Why Is Stat = "Identity" Necessary in Geom_Bar in Ggplot
Email Dataframe as Table in Email Body with Sendmailr
Plot Logistic Regression Curve in R
Generating Multidimensional Data
How to Subset Data.Frames Stored in a List
About Gforce in Data.Table 1.9.2
R - Store a Matrix into a Single Dataframe Cell
Replace Na with 0 in a Data Frame Column
Geom_Point() and Geom_Line() for Multiple Datasets on Same Graph in Ggplot2
Writing to a Dataframe from a For-Loop in R
Increase the API Limit in Ggmap's Geocode Function (In R)
Using Geo-Coordinates as Vertex Coordinates in the Igraph R-Package
Extracting Noun+Noun or (Adj|Noun)+Noun from Text
Order of Legend Entries in Ggplot2 Barplots with Coord_Flip()
Matrix Expression Causes Error "Requires Numeric/Complex Matrix/Vector Arguments"