Daaviid
Daaviid

Reputation: 97

Reshaping my data to introduce a secondary axis (ggplot2)

I'm trying to reshape my data, but I don't know how to do that. Let's use simple data:

a <- c(1,2,3,4,5,6)
b <- c(21.810, 22.086, 21.972, 22.214, 21.871, 22.352)
c <- c(411.6443, 412.8378, 411.9041, 413.6155, 402.0946, 411.6599)
df <- data.frame(a,b,c)

So when I try the following code the result is not what I want (I want the right axis to has the c vector range and the left axis the b vector range).


ggplot() + geom_point(aes(x=df$a, y=df$b))+geom_line(aes(x=df$a , y=df$b))+geom_point(aes(x=df$a, y=df$c))+geom_line(aes(x=df$a , y=df$c))+scale_y_continuous(name = "First Axis",sec.axis = sec_axis( ~.*410.626/22, name="Second Axis"))

EDIT. This is an example of what type of graphic I want

enter image description here

How can I do it?

Upvotes: 1

Views: 75

Answers (1)

TarJae
TarJae

Reputation: 78917

Update II due to concerns of tjebo please see comments: More proper way:

  1. Make transformation in df
  2. bring into long format
  3. remove y aes from geom_line()
df1 <- df %>% 
  mutate(c_transformed = c/(410.626/22)) %>% 
  pivot_longer(
    cols = c(b, c_transformed),
    names_to = 'names',
    values_to = 'value'
  ) %>% 
  arrange(names) 

p <- ggplot(df1, aes(x = a, y = value, color = names)) + 
  geom_line() +   
  scale_color_manual(values = c("blue", "red")) + 
  scale_y_continuous(sec.axis = sec_axis(~.*(410.626/22), name = "second y")) +
  theme_classic()
p

enter image description here

Update: Op edit of question:

Something like this?

ggplot(df, aes(x = a))+ 
  geom_line(aes(y = b, color = "b")) +
  geom_line(aes(y = c/(410.626/22), color = "c")) +
  scale_y_continuous(sec.axis = sec_axis(~.*(410.626/22), name = "second y")) +
  theme_classic()

enter image description here

First answer: Please consider the comments by tjebo. But here is a solution how you can do it:

ggplot(df, aes(x = a))+ 
  geom_line(aes(y = b)) +
  geom_point(aes(y =b)) +
  geom_line(aes(y = c/10)) +
  geom_point(aes(y =c/10))+ 
  scale_y_continuous(sec.axis = sec_axis(~.*10, name = "second y"))

enter image description here

data:

a <- c(1,2,3,4,5,6)
b <- c(21.810, 22.086, 21.972, 22.214, 21.871, 22.352)
c <- c(411.6443, 412.8378, 411.9041, 413.6155, 402.0946, 411.6599)

df <- data.frame(a,b,c)

Upvotes: 1

Related Questions