LDT
LDT

Reputation: 3088

Assign one column to the primary axis and the other to secondary y-axis in ggplot2

I am fighting this morning on how to set the primary and secondary axis of my ggplot correctly. I have a data that looks like this

df <- data.frame(Day = seq(1:10),
  Temperature = seq(4,7,length=10),
  Moisture = seq(5,9,length=10)) 

   Day Temperature Moisture
1    1    4.000000 5.000000
2    2    4.333333 5.444444
3    3    4.666667 5.888889
4    4    5.000000 6.333333
5    5    5.333333 6.777778
6    6    5.666667 7.222222
7    7    6.000000 7.666667
8    8    6.333333 8.111111
9    9    6.666667 8.555556
10  10    7.000000 9.000000

I simply want to assign the Temperature to the primary y-axis and the Moisture in the secondary y-axis.

My effort so far does not work: Any suggestions are highly appreciated. Previous posts in the topic have not been helpful to me.

ggplot(df,aes(Day)) +
  geom_line(aes(y=Temperature), color="#45BF44") +
  geom_line(aes(y=Moisture),   color="#02BEC4") +
  scale_y_continuous(limits = c(3.5,7),
                     name = "Temp",
                     sec.axis = sec_axis(~ 1.2+ ., name="Moist")) 

enter image description here

I want the 5 of the blue line to be in accordance with the 5 in the secondary axis and not of the primary

Upvotes: 1

Views: 439

Answers (1)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6759

Is this what you expected?

library(ggplot2)
ggplot(df,aes(Day)) +
  geom_line(aes(y=Temperature), color="#45BF44") +
  geom_line(aes(y=Moisture-1.2),   color="#02BEC4") +
  scale_y_continuous(limits = c(3.5,7),
                     name = "Temp",
                     sec.axis = sec_axis(~ 1.2+ ., name="Moist"))

enter image description here

Upvotes: 1

Related Questions