I had produced the following chart, which is created using an xts object.
The code I used was simply
plot(graphTS1$CCLL, type = "l", las = 2, ylab = "(c)\nCC for Investors", xlab = "", main = "Clustering Coefficient at the Investor Level")
I updated my R Studio Package and R version and then by running the same code I got the following chart.
Obviously the two are not the same. Can people help me remove the second Y axis - I do not need that, and remove the automatic heading of 2007-03-01 / 2010-12-01. Numerous attempts of this have failed. I did use zoo.plot but the gridlines and ability and the quarterly marks were removed.
My R version is 3.4.0 (2017-04-21) with the following platform "x86_64-apple-darwin15.6.0". Thanks in advance.
You want to remove the right hand axis. There is an argument in plot.xts(..., yaxis.right = TRUE, ...). So
library('xts')
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#> as.Date, as.Date.numeric
data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')
plot(sample.xts, yaxis.right = FALSE)
does what you want.
I took a stab at solving the second question, removing the label at the top right hand side. Examining the source code for plot.xts() reveals that label is hardcoded into the main title. Even setting main = '' isn't going to remove it. You can work around it by editing plot.xts() and copying it to a new function.
plotxts <- fix("plot.xts")
# In the editor that opens, replace the lines below:
### text.exp <- c(expression(text(xlim[1], 0.5, main, font = 2,
### col = theme$labels, offset = 0, cex = 1.1, pos = 4)),
### expression(text(xlim[2], 0.5, paste(start(xdata[xsubset]),
### end(xdata[xsubset]), sep = " / "), col = theme$labels,
### adj = c(0, 0), pos = 2)))
### cs$add(text.exp, env = cs$Env, expr = TRUE)
# with these lines:
### text.exp <- expression(text(xlim[1], 0.5, main, font = 2,
### col = theme$labels, offset = 0, cex = 1.1, pos = 4))
# Finally, you need to ensure your copy's environment is the xts namespace:
environment(plotxts) <- asNamespace("xts")
plotxts(sample.xts, yaxis.right = FALSE, main = "Main Title")
The second, and perhaps
simpler option is to use a different plot function and modify it to produce the gridlines etc that you want. I will start
with plot.zoo() because it is already handling time series nicely.
zoo::plot.zoo(sample.xts, screens = 1, xlab="", las=2, main="Main Title")
grid() # add the grid
That at least gets the grid on there. I can't test if it will handle the x axis labels the same way without data at the right frequency.
You can now (finally) omit the date range from the plot in xts 0.12.2 on CRAN. Set main.timespan = FALSE.
plot(sample.xts[,1], yaxis.right = FALSE, main = "Main Title", main.timespan = FALSE)
Related
I want to plot a animated 3D scatterplot and save it as gif. I followed the code provided by the R Graph Gallery example: https://www.r-graph-gallery.com/3-r-animated-cube.html.
library(rgl)
library(magick)
options(rgl.printRglwidget = TRUE)
# Let's use the iris dataset
# iris
# This is ugly
colors <- c("royalblue1", "darkcyan", "oldlace")
iris$color <- colors[ as.numeric( as.factor(iris$Species) ) ]
# Static chart
plot3d( iris[,1], iris[,2], iris[,3], col = iris$color, type = "s", radius = .2 )
# We can indicate the axis and the rotation velocity
play3d( spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),startTime = 0, duration = 10 )
# Save like gif
movie3d(
movie="3dAnimatedScatterplot",
spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),
startTime = 0,
duration = 10,
dir = ".",
type = "gif",
clean = T,
fps=10,
convert=T
)
plot3d was successed output a 3d scatter plot.
Static 3d scatter plot
But the final output: 3dAnimatedScatterplot.gif,just a black image
3dAnimatedScatterplot.gif
when I set clean=F, all frame images are black. So, I guess the play3d() was not working.
Can anyone provide any help to me ? Thanks a lot !
Most likely snapshot3d isn't working for you. Try it with the option webshot = FALSE instead of the default webshot = TRUE. That uses a different mechanism for saving the image.
I am trying to plot percentages in a simple 2x2 contingency table with vcd::mosaic but I keep getting a Viewport error. Here is how to reproduce (I work on Ubunto 20.04 and R 3.6.3):
t0 <- as.table(rbind( c(221,47), c(17,9) ))
names(dimnames(t0)) = c("X", "C")
rownames(t0) = c("neg", "pos")
colnames(t0) = c("neg", "pos")
library(vcd)
labs <- round(prop.table(t0, 1), 2)
mosaic(t(t0), split = TRUE, shade = TRUE, pop = FALSE )
labeling_cells(text = labs, margin = 0)(t0)
and I get with the last command:
labeling_cells(text = labs, margin = 0)(t0)
Error in grid.Call.graphics(C_downviewport, name$name, strict) :
Viewport 'cell:X=neg,C=neg' was not found
Does anybody know why?
You visualized the transposed table t(t0) with mosaic() but then try to add labeling_cells() for the original table t0. As the two tables don't match, the labeling cannot find the viewports it expects. Simply use t(t0) for the labeling as well:
mosaic(t(t0), split = TRUE, shade = TRUE, pop = FALSE)
labeling_cells(text = labs, margin = 0)(t(t0))
When using chartSeries, by default it also shows on the top left of the plot the last value. Is there any way to prevent it from doing it?
When adding a new TA with addTA, you can avoid the last value on the plot by setting the argument legend = "", but only if you're making a new plot for the TA. If the TA is on a previously plotted graphic, it'll show the last value regardless of what you put in the legend argument.
getSymbols ("AAPL", src = "google")
chartSeries(AAPL)
What can I use here to prevent it from printing the last value on the plot?
addTA(EMA(Cl(AAPL)), on = 1, legend = "")
This still prints the last value on the top left of the plot. The weird part is that it doesn't do it if you're plotting on a new plot like this:
addTA(EMA(Cl(AAPL)), legend = "")
Is it like this by default, or is there something I can do to get around it?
The last value is shown by default (yes, annoyingly). You'll likely have to modify the source code to remove the last number showing in addTA.
I don't use addTA, but rather add_TA and chart_Series, because I think they look much better (second generation charts for quantmod). Here is a solution that removes the last number from showing for the add_TA version. But you must be willing to modify the source code.
In add_TA, you'll need to modify approximately lines 56-60 of the source:
Replace the text.exp, which is this:
# this is inside add_TA:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(1, 1 + strwidth(name)),
y = 0.3, labels = c(name, round(last(xdata[xsubset]),
5)), col = c(1, col), adj = c(0, 0), cex = 0.9,
offset = 0, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
with these modifications:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(strwidth(name)), # <- affects label on the subchart
y = 0.3, labels = name, col = c(col), adj = c(0), cex = 0.9,
offset = 1, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
expr = TRUE)
...
and assign this modified code to a new variable, called say add_TA.mine:
add_TA.mine <- function (x, order = NULL, on = NA, legend = "auto", yaxis = list(NULL,
NULL), col = 1, taType = NULL, ...)
{
lenv <- new.env()
lenv$name <- deparse(substitute(x))
lenv$plot_ta <- function(x, ta, on, taType, col = col, ...) {
xdata <- x$Env$xdata
....
[all the code for the rest of the function with modifications]....
}
}
plot_object
}
Now, just run the code with the modified function
library(quantmod)
getSymbols("AAPL")
environment(add_TA.mine) <- environment(get("add_TA", envir = asNamespace("quantmod")))
assignInNamespace(x = "add_TA", value = add_TA.mine, ns = "quantmod")
chart_Series(AAPL, subset = "2017")
add_TA(RSI(Cl(AAPL)))
quantmod:::add_TA(RSI(Cl(AAPL)))
You can see the last value is no longer printed:
(You could make the same kinds of changes in the old addTA code (perhaps via chartSeries if you really want to stick to the old plots)
If you're happy with the changes, and want to make them permament in add_TA, you can recompile the quantmod source code yourself with your modifications (i.e. you need to download the quantmod source code and recompile the package) . If you make a mess of things you can always redownload the original quandmod source code again.
I am plotting a time series with the timePlot function of the open air package of R. The graph has grey grid lines in the background that I would like to turn off but I do not find a way to do it. I would expect something simple such as grid = FALSE, but that is not the case. It appears to be rather complex, requiring the use of extra arguments which are passed to xyplot of the library lattice. I believe the answer lies some where in the par.settings function but all attempts have failed. Does anyone have any suggestions to this issue?
Here is by script:
timeozone <- import(i, date="date", date.format = "%m/%d/%Y", header=TRUE, na.strings="")
ROMO = timePlot(timeozone, pollutant = c("C7", "C9", "C10"), group = TRUE, stack = FALSE,y.relation = "same", date.breaks = 9, lty = c(1,2,3), lwd = c(2, 3, 3), fontsize = 15, cols = c("black", "black"), ylab = "Ozone (ppbv)")
panel = function(x, y) {
panel.grid(h = 0, v = 0)
panel.xyplot(x,y)
}
I am trying to follow help and Internet examples to create a very simple animation of a 3d-line in R. This is just a test and my final goal is to use this functionality to visually verify results of some geometrical transformations on 3d-movement data that I am analysing. So basically I need nothing more than a ‘3d-player’ interface that allows for usual interaction (rotation, zoom, play, stop, slide).
I figured out that rgl package does the job and I am able to use it for the sphere/points animation. But now I need to use it on lines and I get very strange results. In the example below there are 4 points and two lines (cyan and red) that connect the same points but the red line is for some reason in the ‘wrong’ place. The animation doesn’t make sense neither. Now, I am thinking may be it is impossible to do >> to animate more than one vertex with more than one attribute? But I don’t see this in documentation and obviously it is possible because line is animated! I spent quite a long time trying to figure out what is going on and will appreciate any help/advise/directions. many thanks
Ps: Tthe code below is a chunk in the markdown file and I am using Rstudio.
require(rgl)
require(rglwidget)
p11=c(0,0,0)
p21=c(50,50,0)
p12=c(50,0,0)
p22=c(10,50,50)
saveopts <- options(rgl.useNULL = TRUE)
did=list()
did[[1]]=plot3d(rbind(p11,p21,p12,p22), type="s", alpha = 1, lwd = 5, col = c('brown','darkgreen','orange','green'))
did[[2]]=spheres3d(c(100,100,100), alpha = 1, lwd = 5, col = "blue",radius=2)
did[[3]]=lines3d(rbind(p11,p21),lwd=8, col='cyan',alpha=.9)
did[[4]]=planes3d(0, 0, 1, 0, alpha=.4, col='green')
did[[5]]=lines3d(rbind(p11,p21),lwd=2, col='red')
aspect3d(1, 1, 1)
did[[6]]=grid3d(c("x-", "z-"),at = NULL,col = "gray",lwd = .5,lty = 1,n = 5)
sceneT = rglwidget(elementId = "plot3dT",width=500, height=300) #%>%
rgl.ids()
rgl.attrib(id=did[[3]],attrib = c(1:length(did[[3]])))
playwidget(sceneT,list(
vertexControl(values = rbind(c(0,0,0,0,0,0),c(50,50,50,50,50,50)),
vertices = 1:6, attributes = "z", objid = did[[4]], param = 1:2,interp =T),
vertexControl(values = r1,
vertices = 1:2, attributes = c('x',"y","z",'x',"y","z"), objid = did[[5]], param = 1:2,interp =T)),
start = 1, stop = 2, step = .1, precision = 3)
options(saveopts)