[R] Split charts with ggplot2, tidyquant

Charlie Redmon redmonc at gmail.com
Fri Jan 19 17:33:56 CET 2018


So the general strategy for getting these into separate panels in ggplot 
is to have a single variable that will be your response and a factor 
variable that indexes which original variable it came from. This can be 
accomplished in many ways, but the way I use is with the melt() function 
in the reshape2 package.
For example,

library(reshape2)
plotDF <- melt(SPYdf,
                         id.vars="Date", # variables to replicate
                         measure.vars=c("close", "volume"), # variables 
to create index from
                         variable.name="parameter", # name of new 
variable for index
                         value.name="resp") # name of what will be your 
response variable

Now the ggplot2 code:

library(ggplot2)
ggplot(plotDF, aes(x=Date, y=resp)) +
     facet_wrap(~parameter, ncol=1, scales="free") +
     geom_line()


Hope that does the trick!

Charlie


On 01/18/2018 02:11 PM, Eric Berger wrote:
> Hi Charlie,
> I am comfortable to put the data in any way that works best. Here are 
> two possibilities: an xts and a data frame.
>
> library(quantmod)
> quantmod::getSymbols("SPY")  # creates xts variable SPY
> SPYxts <- SPY[,c("SPY.Close","SPY.Volume")]
> SPYdf  <- 
> data.frame(Date=index(SPYxts),close=as.numeric(SPYxts$SPY.Close),
>  volume=as.numeric(SPYxts$SPY.Volume))
> rownames(SPYdf) <- NULL
>
> head(SPYxts)
> head(SPYdf)
>
> #           SPY.Close SPY.Volume
> #2007-01-03    141.37   94807600
> #2007-01-04    141.67   69620600
> #2007-01-05    140.54   76645300
> #2007-01-08    141.19   71655000
> #2007-01-09    141.07   75680100
> #2007-01-10    141.54   72428000
>
> #        Date  close   volume
> #1 2007-01-03 141.37 94807600
> #2 2007-01-04 141.67 69620600
> #3 2007-01-05 140.54 76645300
> #4 2007-01-08 141.19 71655000
> #5 2007-01-09 141.07 75680100
> #6 2007-01-10 141.54 72428000
>
> Thanks,
> Eric
>
>
>
> On Thu, Jan 18, 2018 at 8:00 PM, Charlie Redmon <redmonc at gmail.com 
> <mailto:redmonc at gmail.com>> wrote:
>
>     Could you provide some information on your data structure (e.g.,
>     are the two time series in separate columns in the data)? The
>     solution is fairly straightforward once you have the data in the
>     right structure. And I do not think tidyquant is necessary for
>     what you want.
>
>     Best,
>     Charlie
>
>     -- 
>     Charles Redmon
>     GRA, Center for Research Methods and Data Analysis
>     PhD Student, Department of Linguistics
>     University of Kansas
>     Lawrence, KS, USA
>
>

-- 
Charles Redmon
GRA, Center for Research Methods and Data Analysis
PhD Student, Department of Linguistics
University of Kansas
Lawrence, KS, USA



More information about the R-help mailing list