Reputation: 5
I'm having some problems to plot a complex plot. Here's the dataset: https://mega.nz/file/758V3a5B#tgaFZAI5jQKn_As10ZkzvPwCH-7zG6X9M_dQH5gmALc
I want to make a ggplot with 3 layers:
On the x-axis I want the variable "Date" Then I would like to have two scale on y-axis. First on the left y-axis I want to put the variable "Close" and on the right y-axis I want to put the variable "P.S_EW" with a line. Then an additional layer with the density of the variable "P.S_tc" given that on the x-axis there's always the variable "Date". I really can't figure out how to do this. Hope someone can help and sorry for my poor english.
-- EDIT -- The dataset is available in the link mega.nz above. I tried to compute the density of P.S_tc with density() and then tried to merge to the original dataset by "Date" but it doesn't work. I've been able to plot close and P.S_EW with the following script
plot.close <- xyplot(Close ~ Date, data, type = "l")
plot.conf <-xyplot(as.formula(paste("P.S_EW","~","Date",sep=""))
, data, type = "l")
plot_ <- update(doubleYScale(plot.close,plot.conf,
text=c("Price","P.S_EW"),add.ylab2 = TRUE, use.style=TRUE),
par.settings = simpleTheme(col = c('black','red')))
But I can't add the density. Maybe the approach to compute the density separately with density() and then merge (in some ways) to the original dataset BY "Date" would work beacause then you only have to add another layer in ggplot. But I wasn't able to merge the density to the data properly. The image below is what i got from the previous script.
https://i.sstatic.net/nE2Qc.jpg
Upvotes: 0
Views: 892
Reputation: 79224
This is the max I can produce so far. I have problems to plot density of P.S_tc
as a layer because the x axis of a density plot is the variable itself: so in your case Date
(desired x axis) competes with P.S_tc
:
library(ggplot2)
library(hrbrthemes)
# Value used to transform the data
coeff <- 10000
# constants
CloseColor <- "#69b3a2"
P.S_EWColor <- rgb(0.2, 0.6, 0.9, 1)
p <- ggplot(example, aes(x=Date)) +
geom_line( aes(y=Close), size=1, color=CloseColor) +
geom_line( aes(y=P.S_EW * coeff), size=1, color=P.S_EWColor) +
scale_y_continuous(
# Features of the first axis
name = "Close",
# Add a second axis and specify its features
sec.axis = sec_axis(~.*coeff, name="P.S_EW ($)")
) +
theme_ipsum() +
theme(
axis.title.y = element_text(color = CloseColor, size=13),
axis.title.y.right = element_text(color = P.S_EWColor, size=13)
) +
ggtitle("Close, P.S_EW")
Upvotes: 1