0

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"))

enter image description here

Questions:

  1. How can I add a legend on the top left within the graph?
  2. 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!

Christopher
  • 2,120
  • 7
  • 31
  • 58

2 Answers2

4

Please note that these are two very different questions, it would have been better to split them.

You need to put both color inside the aes(), use then theme(legend.position = c(0.9, 0.2)) to move the legend.

Note that the colors now won't correspond (they are just "labels"), you should to define your own color scale and legend with scale_color_manual().

ggplot(mtcars, aes(x=disp)) +
  labs(title = "My Plot") +
  geom_smooth(aes(y=cyl, col="blue"), method="loess") +
  geom_smooth(aes(y=hp * scaleFactor, col="red"), method="loess") +
  scale_y_continuous(name="cyl", sec.axis=sec_axis(~./scaleFactor, name="hp")) +
  theme(legend.position = c(0.9, 0.2)) +
  scale_x_continuous(expand = c(0, 0)) 

enter image description here

Error in as.Date.numeric(value) : 'origin' must be supplied"

Is probably because x in that case is as.Date type, scale_x_date(expand = c(0, 0)) works.

Here an example:

set.seed(123)
dat <- data.frame(
  dates = seq(from=as.Date("2018-01-01"), to=as.Date("2018-01-10"), by="day"),
  val1 = sample(10),
  val2 = sample(10)
)

ggplot(dat, aes(x=dates)) +
  geom_line(aes(y=val1, color = "red")) +
  geom_line(aes(y=val2, color = "blue")) +
  theme(legend.position = c(0.9, 0.2)) +
  scale_x_date(expand = c(0,0)) +
  scale_y_continuous(name="val2", sec.axis=sec_axis(~./1, name="val2"))

enter image description here

RLave
  • 8,144
  • 3
  • 21
  • 37
1

To add to RLave's answer, the labels assigned in the legend you'll notice don't correspond to colour. To change this, assign the col= commands in aes to the label text, and add scale_fill_manual to choose the colours:

ggplot(mtcars, aes(x=disp)) +
  labs(title = "My Plot") +
  geom_smooth(aes(y=cyl, col="cyl"), method="loess") +
  geom_smooth(aes(y=hp * scaleFactor, col="hp"), method="loess") +
  scale_color_manual(values = c("blue", "red"))+
  scale_y_continuous(name="cyl", sec.axis=sec_axis(~./scaleFactor, name="hp"))
Andy Baxter
  • 5,833
  • 1
  • 8
  • 22