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)
Related
I am having problems using ggplot with Rmarkdown.
I have a code that is supposed to return a ggplot graph.When I execute the code in a R session it works but the same code returns an empty plot when using R markdown.This is the code I am using in the R session
m<-ggplot(data=t,aes_string(x=v,y =t$cnt_pct))
m+geom_bar(stat = "identity",fill="#FF0000",color='black')+geom_text(aes(label = cnt_pct),vjust=-0.2)+ggtitle(paste(v,paste("graph")))+theme(plot.title = element_text(hjust = 0.5))+ylab("percent")+geom_line(aes_string(x=v,y =t$keshel_pct),group=1,size=2)
This is the code I am using in the Rmarkdown
m<-ggplot(data=t,aes_string(x=v,y =t$cnt_pct))
m+geom_bar(stat = "identity",fill="#FF0000",color='black')+geom_text(aes(label = cnt_pct),vjust=-0.2)+ggtitle(paste(v,paste("graph")))+theme(plot.title = element_text(hjust = 0.5))+ylab("percent")+geom_line(aes_string(x=v,y =t$keshel_pct),group=1,size=2)
plot(m)
The only diffrence between the two is that with the Rmarkwond a plot(m) line is added.
For some reason the plot command makes the graph empty, when I remove it and run the Rmarkdown no graphs are returned.
This is the graph empty
This is the graph working in a session of R
Anybody has any idea what is my mistake?
Any help will be appriciated
You have a few issues here:
1) your plot syntax has issues. aes_string takes strings referring to column names, but you're passing a variable v for x and direct column data t$cnt_pnt for y. Check some ggplot examples to get the syntax right.
2) The plot(m) statement shouldn't work for two reasons: first, you print ggplot objects, not plot them. Second, you are not assigning the m + geom_bar(...) statement to anything, so even if your plot statement did work, you'd get the plot without the geom_bar(...) stuff. Try e.g. y = m+ geom_bar(...); print(y) instead.
I have a problem working with plotting time series in Julia.
I am currently using v. 0.6 and the following minimal example
using TimeSeries
using MarketData
plot(ohlcv["Open"])
results in the errormessage:
ArgumentError: Millisecond: 63082540800000 out of range (0:999)
Please help
Thanks a lot!
Seems like a bug.
For now, you can get a decent plot by converting to Float and treating the Dates as labels though:
using TimeSeries, MarketData, PyPlot
O = ohlcv["Open"];
Timestamps = [Float64(t) for t in O.timestamp];
Timestamplabels = [string(t) for t in O.timestamp];
plot(Timestamps, O.values);
xticks(Timestamps[1:div(end,4):end], Timestamplabels[1:div(end,4):end]);
PS. You didn't specify what plot backend you're using, so I assumed PyPlot for this example. Your xtick method may vary for other backends (e.g. xticks! for Plots.jl)
This was a 0.6-related bug in Plots - it is fixed now, and the code in the original question works again.
Temporal is another time series package that has plotting functionality. (It integrates with the Plots package using RecipesBase). Some example usage below:
using Temporal
X = quandl("CHRIS/CME_CL1") # get historical crude oil prices
x = X["2015/", :Settle] # get the settle prices from 2015 onward
using Plots
plotlyjs()
plot(x)
using Indicators
m = mama(x) # mesa adaptive moving average
plot!(m)
I need to repeat the thing done in:
tiny pie charts to represent each point in an scatterplot using ggplot2 but I stumbled into the problem that the package ggsubplot is not available for 3.3.1 R version.
Essentially I need a histogram or a pie chart in predefined points on the scatterplot. Here is the same code that is used in the cited post:
foo <- data.frame(X=runif(30),Y=runif(30),A=runif(30),B=runif(30),C=runif(30))
foo.m <- melt(foo, id.vars=c("X","Y"))
ggplot(foo.m, aes(X,Y))+geom_point()
ggplot(foo.m) +
geom_subplot2d(aes(x = X, y = Y, subplot = geom_bar(aes(variable,
value, fill = variable), stat = "identity")), width = rel(.5), ref = NULL)
The code used libraries reshape2, ggplot2 and ggsubplot.
The image that I want to see is in the post cited above
UPD: I downloaded the older versions of R (3.0.2 and 3.0.3) and checkpoint package, and used:
checkpoint("2014-09-18")
as was described in the comment bellow. But I get an error:
Using binwidth 0.0946
Using binwidth 0.0554
Error in layout_base(data, vars, drop = drop) :
At least one layer must contain all variables used for facetting
Which I can't get around, because when I try to include facet, the following error comes up:
Error: ggsubplots do not support facetting
It doesn't look like ggsubplot is going to fix itself any time soon. One option would be to use the checkpoint package, and essentially "reset" your copy of R to a time when the package was compatible. This post suggests using a time point of 2014-09-18.
I have a bit of R-code to make a heatmap from a correlation matrix, which worked the last time I used it (prior to the 2013 Oct 17 update of gplots; after updating to R Version 3.0.2). This makes me think that something changed in the most recent gplots update, but I can not figure out what.
What used to present a nice plot now gives me this error:
" Error in hclustfun(distfun(x)) : could not find function "distfun" "
and won't plot anything. Below is the code to reproduce the plot (heavily commented as I was using it to teach an undergrad how to use heatmaps for a project). I tried adding the last line to explicitly set the functions, but it didn't help resolve the problem.
EDIT: I changed the last line of code to read:
,distfun =function(c) {as.dist(1-c,upper=FALSE)}, hclustfun=hclust)
and it worked. When I used just "dist=as.dist" I got a plot, but it wasn't sorted right, and several of the dendrogram branches didn't connect to the tree. Not sure what happened, or why this is working, but it appears to be.
Any help would be greatly appreciated.
Thanks in advance,
library(gplots)
set.seed(12345)
randData <- as.data.frame(matrix(rnorm(600),ncol=6))
randDataCorrs <- randData+(rnorm(600))
names(randDataCorrs) <- paste(names(randDataCorrs),"_c",sep="")
randDataExtra <- cbind(randData,randDataCorrs)
randDataExtraMatrix <- cor(randDataExtra)
heatmap.2(randDataExtraMatrix, # sets the correlation matrix to use
symm=TRUE, #tells whether it is symmetrical or not
main= "Correlation matrix\nof Random Data Cor", # Names plot
xlab= "x groups",ylab="", # Sets the x and y labels
scale="none", # Tells it not to scale the data
col=redblue(256),# Sets the colors (can be manual, see below)
trace="none", # tells it not to add a trace
symkey=TRUE,symbreaks=TRUE, # Tells it to keep things symmetric around 0
density.info = "none"#) # can be "histogram" if you want a hist of your corr values here
#,distfun=dist, hclustfun=hclust)
,distfun =function(c) {as.dist(1-c,upper=FALSE)}, hclustfun=hclust) # new last line
I had the same error, then I noticed that I had made a variable called dist, which is the default call for distfun= dist. I renamed the variable and then everything ran fine. You likely made the same error, as your new code is working since you have altered the default call of distfun.
Jeff Ryan's quantmod package is an excellent contribution to the R finance world.
I like to use chartSeries() function, but when I try to get it to display multiple panes simultaneously, it doesn't work.
par(mfrow=c(2,2))
chartSeries (SPX)
chartSeries (SPX, subset="2010")
chartSeries (NDX)
chartSeries (NDX, subset="2010")
would normally return a four-panel graphic as it does with the plot() function but in the chartSeries example it runs through all instances one at a time without creating a single four-panel graphic.
use chart_Series() instead of chartSeries() it is layout() and par() compliant.
No, sadly, you cannot (unless this changed very recently).
The power of adding new sub-panels comes at the prices of not being able to combine these plots as you otherwise could in base graphics.
But you could re-create them in base graphics and then the par(mfrow=...) etc idioms would be available to you.
I will just add to Brian G. Peterson's post a working quantmod code example for creating chart_Series plots in multiple panels:
# download data and copy it into environment
sym_bols <- c("IEF", "VTI", "XLP", "XLF", "XLK", "VXX")
data_env <- new.env()
quantmod::getSymbols(sym_bols, env=data_env, from="2017-01-01")
# create chart_Series plots in multiple panels
x11()
par(mfrow=c(3, 2))
par(mar=c(2, 2, 2, 1), oma=c(0, 0, 0, 0))
eapply(data_env, function(x) {
plot(quantmod::chart_Series(x["2017-06/"],
name=strsplit(colnames(x)[1], split="[.]")[[1]][1]))
}) # end eapply
Note that chart_Series must be wrapped in plot.
Produces the following plot: