I currently use following script to plot a graph with one common x and two distinct y-axes:
library(ggplot2)
library(scales)
scaleFactor <- max(mtcars$cyl) / max(mtcars$hp)
ggplot(mtcars, aes(x=disp)) +
labs(title = "My Plot") +
geom_smooth(aes(y=cyl), method="loess", col="blue") +
geom_smooth(aes(y=hp * scaleFactor), method="loess", col="red") +
scale_y_continuous(name="cyl", sec.axis=sec_axis(~./scaleFactor, name="hp"))
Questions:
- How can I add a legend on the top left within the graph?
- How can I remove the spacing to the left and right of the x-axis? Note:
+ scale_x_continuous(expand = c(0, 0))
works perfectly in the example above, but in any other given time series, it returns *"Error in as.Date.numeric(value) : 'origin' must be supplied"`.
Thank you!