Need help fixing the plot for a simple curve() function code - r

I am trying to plot four separate functions on the same graph using the curve() function in r. I came up with the following code:
for (n in 1:4){
curve(n*sin(x), -5, 5, add = TRUE)
}
Unfortunately, when I try that, the resulting plot is extremely zoomed in on one arbitrary point of the graph (axes labels nor graph borders can be seen either). Just to clarify, there is no resulting error message in the console at all, the plot is just very zoomed in.
Instead of plotting them in a for loop, I tried plotting them separately to see if it would work and it did. I used:
curve(4*sin(x), -5, 5)
curve(3*sin(x), -5, 5, add = TRUE)
curve(2*sin(x), -5, 5, add = TRUE)
curve(1*sin(x), -5, 5, add = TRUE)
I had also thought that it could be that I used curve() in a for loop; however, it has worked for this code (demonstrating that the function doesn't seem to care whether I use it in a loop-type function):
for (n in 0:5){
curve(x^n, -3, 3, add = TRUE)
}
Besides trying out different code, I have closed my graphics device, turned it off with dev.off(), restarted RStudio, but none of it has worked.
If I were only using a sequence from 1 to 4, like I mentioned above, I wouldn't care about typing them separately; however, I plan on using a much larger range of sequences in the future (like 1:50 or 1:100 for example).
I'm using RStudio version 3.4.4 with macOS 10.14.2 if that matters.

Related

PlotlyJS fails to produce a plot in Julia

I came across with an odd situation that I can't understand. Running Julia 1.7.3 under Ubuntu 22.04. I have one file.jl that contains the code below. The code in area1() produces a plot. But the code in bizarre() does not. I have tried this from xTerm and under VSC. In both cases area1() plots OK but bizarre() does not.
This is driving me crazy. Any help/suggestion greatly appreciated. Thank you
using DataFrames
using Statistics
using LinearAlgebra
using PlotlyJS
function area1()
trace1 = scatter(;x=1:4, y=[0, 2, 3, 5], fill="tozeroy")
trace2 = scatter(;x=1:4, y=[3, 5, 1, 7], fill="tonexty")
plot([trace1, trace2])
end
function bizarre()
println("Start Bizarre")
trace1 = scatter(;x=1:4, y=[0, 2, 3, 5], fill="tozeroy")
trace2 = scatter(;x=1:4, y=[3, 5, 1, 7], fill="tonexty")
plot([trace1, trace2])
println("End of Bizarre")
end
The confusion stems from the fact that plot is not a plotting function. plot is a Plot-creation function i.e. it creates a Plot object with the data and characteristics you specify. It does not by itself create a figure on the screen. That is the job of the display function.
When you call area1 from the REPL in xTerm (and whatever equivalent is used in VSCode), the REPL automatically calls display on the return value of the function. This is true for any function call, and is the "print" part of "read-eval-print-loop". And functions in Julia automatically return the value of the last expression they evaluate. So, in area1, since the plot call is on the last line, the resulting Plot object is returned, and then automatically displayed by the REPL.
In bizarre, the last statement is a println, which returns nothing, so nothing is printed or displayed. The statement before that, the plot call, just creates a Plot object, but doesn't display it, so it's just created and thrown away. If you replace that line with display(plot([trace1, trace2])), you'll see that that function produces a plot too.

Strange blue subtitle when plotting objects from the RandomFields package

Theplot method for RFspatialGridDataFrame outputs a weird blue "subtitle" when passing main or axis label arguments to the plot function.
install.packages("RandomFields")
library(RandomFields)
model <- RPbernoulli(RMexp(scale = 3), threshold = 1)
set.seed(100)
simulation <- RFsimulate(model, x = 1:138, y = 1:74)
plot(simulation, main = "This is an example title")
The following is a screeshot of the output
Strangely enough, this appears to be a feature, as running other example for the RandomFields documentation shows.
Is there any way of not outputting this blue repeated title? I have tried fiddling with other graphical arguments (such as setting legend = F) but the behavior does not change.
I have contacted the maintainers of the RandomFields package, and it appears to be a setting in RFoptions.
By setting RFoptions(grPrintlevel = 0) before the plots, this behavior can be avoided. More information can be found under ?RFoptions in section 10 regarding graphics. The relevant part regarding grPrintlevel reads
grPrintlevel: integer values 0, 1, 2; only relevant when simulations are
plotted. The higher the more text is shown in the plot.
Default: 1.

Text not appearing on XTS plot

I'm having trouble adding some text to an plot of time series data in R using xts. I've produced a simple example of the problem.
My text() command seems to do nothing, whereas I can add a points to the plot. I've tried to keep the code simple by using defaults where possible
require(quantmod)
# fetch the data and plot it using default options
getSymbols('MKS.L')
plot(MKS.L$MKS.L.Close)
# try to add text - doesn't appear
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)
# add a point - this does appear
testPos <- xts(600, as.Date('2012-01-01'))
points( testPos, pch = 3, cex = 4, col = "red" )
Any help appreciated - I'm pretty new to R and I've spent hours on this!
Not a direct answer, but the plot.xts function that comes with the xts package is not fully developed.
You're much better off using plot.zoo or plot.xts from the xtsExtra package (which was written as a Google Summer of Code project with the intention being to roll it into the xts package)
Either of these will work:
plot(as.zoo(MKS.L$MKS.L.Close))
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)
#install.packages("xtsExtra", repos="http://r-forge.r-project.org")
xtsExtra::plot.xts(MKS.L$MKS.L.Close)
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)

R 2.14.1 OS X dens() of lessR does not take sample() data as input

R version 2.14.1    Platform: i386-apple-darwin9.8.0/i386 (32-bit)
Objective:
Use function dens() of library lessR to plot a normal density curve and a general density curve superimposed over a histogram.
Problem:
While generating the data using e.g. rnorm() or rbinom() works well, running it on data generated by sample() returns this error:
Error in if (from == to) rep.int(from, length.out) else as.vector(c(from, :
argument is of length zero
MWE:
library(lessR)
data <- data.frame(col=sample(20))
y <- data$col
dens(y)
Question:
What causes the problem and what do I have to do if I want to have a data frame with a single column, let us say, which would contain twenty rows of values generated by the sample() function and use them as an input for the dens()?
Update (2012-11-17):
I have updated R to version 2.15.2 and lessR to version 2.6 (both are the latest available).
Using the data provided by #Roland, the error is now:
Error in seq.default(x.min, x.max, length = 200) :
'from' must be of length 1
I can understand why it does happen and allowing sample() to use a single value more than one leads to a correct result.
Yes, as the developer of lessR I found the bug. What happened is that I had a > and a < condition for centering the density plot, but no = condition. This = condition was triggered from the call to sample(20) because the result was the sequential integers from 1 to 20. Obviously a valid set, but one which triggered the = condition in my code and a condition that I had not previously tested. Changing a > to >= has fixed the bug. The fix will be on CRAN when I upload the next version around Dec 10. The maintainers are discouraging frequent updates to CRAN, so I need to wait until Dec to update.
For now, if you wish to get a density plot using your example, run the following R code.
y <- sample(20)
dy <- density(y)
plot(dy)
Also, when I began this project almost 4 years ago, I did not have a plan to produce a systematic system for data analysis with about 43 different functions. As such my initial naming schemes for functions did not generalize very well as the system grew from just a few functions, so I have gradually evolved a system that will not change in the future. Each function can be referred to by its full name, such as Density, or now by a usual two character abbreviation, dn in this case. I decided for consistency sake to make the abbreviations two characters, which are also lower case. The goal is to produce standard data analysis procedures such as a Histogram or hs, a ScatterPlot or sp, a BoxPlot or bx with very little work and with provided color themes for the graphs. The default color theme is blue, but can be changed easily with the set function.
The current version of lessR appears not to provide a function dens anymore, instead there is a function Density.
Would you consider updating your R version and the package? Why are you using the 32-bit version of R? On a Mac you should be able to use the 64-bit version.
I had a look at function dens from lessR_2.1.1. I could not reproduce your error (because you did not use set.seed to make your code reproducible). Instead I got Error in seq(min.x, max.x, length = 200) : Object 'min.x' not found with y <- c(3, 4, 8, 1, 6, 14, 20, 5, 13, 17, 19, 10, 2, 12, 7, 9, 18, 11, 15, 16).
Here is an excerpt from the function code:
d.gen <- suppressWarnings(density(x, bw, ...))
mx <- mean(x)
# min and max x coordinates for graph, make symmetric
min.dev.x <- min(d.gen$x) - mx
max.dev.x <- max(d.gen$x) - mx
if (abs(min.dev.x) > abs(max.dev.x)) {
min.x <- min(d.gen$x)
max.x <- mx + abs(min.dev.x)
}
if (abs(max.dev.x) > abs(min.dev.x)) {
min.x <- mx - abs(max.dev.x)
max.x <- max(d.gen$x)
}
Note that the code does not define min.x and max.x, if abs(min.dev.x) == abs(max.dev.x), which is a bug. Of course that is easily fixed by changing the second if condition to if (abs(max.dev.x) >= abs(min.dev.x)) {.
There might be other bugs, but it's not worth fixing a function from an archived version of a utility package. Of course, I get a similar error with the new Density function and indeed it contains the same bug.

R/quantmod: multiple charts all using the same y-axis

I'm trying to plot 6 days of intraday data as 6 charts. Quantmod's experimental chart_Series() function works with par() settings. I've pre-loaded the data into bars (a vector of XTS objects) so my code looks like this:
par(mfrow=c(3,2)) #3 rows, 2 columns
for(d in bars){
print(chart_Series(d, type = "candlesticks") )
}
This works, but each chart has its own different y-axis scale. I wanted to set a y-range that covers all 6 days, but cannot find a way to do this. I tried this:
ylim=c(18000,20000)
print(chart_Series(d, type = "candlesticks",ylim=ylim) )
but it fails with the "unused argument(s)" error. yrange=ylim also fails.
I can use chartSeries(d,yrange=ylim), and it works. But as far as I know I cannot put multiple charts in one display (?).
(It might strictly be off-subject, but suggestions for alternative R packages that can draw nice-looking candlestick charts, allow y-axis control and can draw multiple charts on one image would also be very welcome.)
With chartSeries, you can set the layout argument to NULL to prevent the layout() command from being called: this is what disables the mfrow setting.
library(quantmod)
getSymbols("AA")
op <- par(mfrow=c(3,2))
for(i in 1:6) {
chartSeries(
AA["2011-01"], "candlesticks",
TA=NULL, # No volume plot
layout=NULL,
yrange=c(15,18)
)
}
par(op)
If you want to keep the volume, you can call layout instead of setting mfrow: it does basically the same thing, but allows you to have plots of different sizes and choose the order in which they are plotted.
layout( matrix( c(
1, 3,
2, 4,
5, 7,
6, 8,
9, 11,
10, 12
), nc=2, byrow=TRUE),
heights = rep( c(2,1), 3 )
)
#layout.show(12) # To check that the order is as desired
for(i in 1:6) {
chartSeries(
AA[sprintf("2011-%02d",i)],
"candlesticks", layout=NULL, yrange=c(15,19)
)
}
Googling to understand Vincent's answer led me to the layout() command. It seems incompatible with par(mfrow), but some more experimentation found it can be used as an alternative.
ylim=c(18000,20000)
layout(matrix(1:12,nrow=6,ncol=2), height=c(4,2,4,2,4,2))
for(d in bars){
chartSeries(d,layout=NULL,TA=c(addVo(),addBBands()),yrange=ylim)
}
(You'll notice I added bollinger bands too, to be sure overlays still work too.)

Resources