add data points to existing plot in R - r

I try to receive the data from a sensor from time to time and plot it in real time. That means the length of the dataset is not know before hand. And need to adjust the range of the graph dynamically.
I tried the following
plot(1,10, xlim=range(0,10), ylim=range(0,10), type='n')
points(1,data[1])
points(2,data[2])
But once the number of dots is beyond the range of x axis (10 in this case), the data points are out of the range. How to adjust the range accordingly?

Just issue a new plot command with an expanded range. On modern computers the time taken to recreate the plot is small and you generally will not see a delay. Any other approach will essentially do the same thing, clear the current plot and create a new plot.
The ggplot2 and lattice packages have ways of constructing a plot and updating the plot, but when the updated plot is shown it is redrawn from scratch.
There is a zoomplot function in the TeachingDemos package which will allow you to change the range of a plot, but it also will just redraw the plot from scratch (and due to changes in R 3.0.0 it is not currently working, so if you wanted to use it you would need to go back to R 2.15 or before, or wait for it to be fixed).

You can't adjust the range dynamically (sometimes Excel is better). However, you can keep track of what you've plotted, and redo the plot when you've reached the limit. You could also just make a new plot every time you get more data, which would be a way of faking a dynamic update.

Related

Can I create a target zone on my time series plots in R?

I've created a time series plot in R using the ggplot package, but I wanted to see if I could further customize it by creating target zones. I originally started with an Excel plot that allows me to move a gray box to different areas of the plot as an easier way to point out a range of temperatures. However, I wanted to see if I could replicate this in R. Here's a screenshot of my Excel plot to better explain my goal: Time Series on Excel. On the time series plot, you can see a gray box that you can drag around and change the size of to better define a range of temperatures (in this case, it covers from 15-25C). Is this possible to do on top of my time series plot in R? I'm only starting to code in R so it's been quite hard for me to navigate, and I appreciate any help I could get. Thanks!

How to draw scrolling graphics in R, like financial time series

I would like to draw financial time series in R, that are continuously updated all along the day. Sometimes I can have several updates per second and I want to draw the time series as it evolves.
Moreover, I want to improve my graphics with extra information that I will plot too on the same graph (not necessarily a time series).
So I wonder if there is either:
a package in R to draw such series and have them scroll automatically as soon as I push new data
or a way to do bit blit in R and simply update my graph,
or a way to use packages like grid or anything else that would draw what is necessary (at least lines and points) and help scroll the data quickly to have a smooth rendering.
I would like something a bit more modern than a TCL/TK solution like explained here
We are doing this with shiny and a timer variable which refreshes the plot every n seconds.
R itself isn't really made for continuous updates. The (default) graphics device is static (so you can't easily 'append one point'), and there is only one event loop.
You can do it with external programs -- I have used both custom Qt applications I wrote for this as well as custom data handler in the (awesome, under-appreciated) kst real-time visualization program.
I'm not on financial data, but if the data file is itself updated along the day, the simplest solution would be something like:
k <- 0
while ( k<=3600 ) {
foo <- read.table("data.txt")
plot(foo[,1], foo[,2])
Sys.sleep(60) # seconds
k <- k+1
}
This would redraw the plot each 60 seconds. You can put a web adress for the data instead of "data.txt" also. To "scroll", you can play with the xlim argument to plot().

Toggling amongst plot spaces

Scenario: Five Graphs for Five Periods {3M, 6M, 1Y, 2Y & 3Y}, each with their own (1-2) scatter plots; sharing the same y-range (values).
Each period has different x-ranges and labeling policies.
For example, one could have either a fix or location policy; another none.
The X-Range appears to be immutable/plot-space. So I'm thinking of creating parallel plot spaces with their particular xRanges & labeling policies.
I studied the relationship of a plot space with the x.axis(s) & plot(s):
Graph <=== {NSMutableArray *plotSpaces}
x.axis/plot-space.
plot/plot-space
So I believe I can:
1) Create a plotspace.
2) Assign the plotspace to a particular plot, x-axis & xRange.
3) add or remove the plot to/from the graph.
4) Redraw the graph.
So when the user selects a period/plotspace, All I need to do is: replace any existing plots with the period plot(s) which will cause the graph to plot the plots & display the respective x-axis (Y-axis is common)?
[myGraph removePlot:(CPTPlot *)oldPlot];
[myGraph addPlot:(CPTPlot *)plot toPlotSpace:(CPTPlotSpace *)space];
...I'm a little lost here.
?
Axes are also assigned to a plot space. You would need to swap out the axes, too. You'll take a relatively large performance hit by adding and removing plots and axes all the time.
As you observed, the plot ranges are immutable. That just means that you can't change an existing range, not that you can't set a new one. Either create a new CPTPlotRange object or make a mutable copy of an existing one.
Whenever you want to change the plot scale, you need to do the following things. These can all change in place, without removing and replacing major pieces of the graph.
Change the plot ranges as described above.
Update the labeling policy and related properties of the axis.
Call -reloadData on the plot to load the new data.

Repeat plot command with minor changes in R

I made a plot in R and I want to repeat all the commands (like plot(), legend() or line()) that were carried out for this plot, with some minor changes. For example I want to set the axes to logarithmic scale and change the title of the plot.
In gnuplot I would use the replot command.
plot ...
set title "The same plot with logarithmic axes"
set logscale
replot
Is something like this possible in R. The only thing that comes to my mind of doing this (besides changing the values manually and re-run the lines of codes) would be setting up a function, that asks for all parameters that might be changed by the user.
Thanks for your help,
Sven
R uses a pen and paper graphics model - once the plot has been drawn on the device that is it. If you want to change some aspect of the plot, you need to replay the graphics function calls that produce the plot with the changes made to the code.
Depending on what you are really doing there are two options:
If this is just for you, write code in a text editor / IDE that knows R and can send chunks of code at a time to R. That way the code to produce the figure is recorded in a separate script which you can paste into/send to R making the changes you need each time to the script.
If you are going to be doing this often, then write yourself a wrapper plotting function that encapsulates the plot code you want but allows you to pass in arguments to alter the aspects you want.
Lattice and ggplot2 are a little different as they are based on grid graphics and create objects that when printed produce a plot on the device. One can manipulate that object to alter what is drawn, and with grid one can push and pop things on to / off a viewport.

How to avoid overplotting (for points) using base-graph?

I am in my way of finishing the graphs for a paper and decided (after a discussion on stats.stackoverflow), in order to transmit as much information as possible, to create the following graph that present both in the foreground the means and in the background the raw data:
However, one problem remains and that is overplotting. For example, the marked point looks like it reflects one data point, but in fact 5 data points exists with the same value at that place.
Therefore, I would like to know if there is a way to deal with overplotting in base graph using points as the function.
It would be ideal if e.g., the respective points get darker, or thicker or,...
Manually doing it is not an option (too many graphs and points like this). Furthermore, ggplot2 is also not what I want to learn to deal with this single problem (one reason is that I tend to like dual-axes what is not supprted in ggplot2).
Update: I wrote a function which automatically creates the above graphs and avoids overplotting by adding vertical or horizontal jitter (or both): check it out!
This function is now available as raw.means.plot and raw.means.plot2 in the plotrix package (on CRAN).
Standard approach is to add some noise to the data before plotting. R has a function jitter() which does exactly that. You could use it to add the necessary noise to the coordinates in your plot. eg:
X <- rep(1:10,10)
Z <- as.factor(sample(letters[1:10],100,replace=T))
plot(jitter(as.numeric(Z),factor=0.2),X,xaxt="n")
axis(1,at=1:10,labels=levels(Z))
Besides jittering, another good approach is alpha blending which you can obtain (on the graphics devices supporing it) as the fourth color parameter. I provided an example for 'overplotting' of two histograms in this SO question.
One additional idea for the general problem of showing the number of points is using a rug plot (rug function), this places small tick marks along the margin that can show how many points contribute (still use jittering or alpha blending for ties). This allows the actual points to show their true rather than jittered values, but the rug can then indicate which parts of the plot have more values.
For the example plot direct jittering or alpha blending is probably best, but in some other cases the rug plot can be useful.
You may also use sunflowerplot, while it would be hard to implement it here. I would use alpha-blending, as Dirk suggested.

Resources