Reputation: 97
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
How can I do it?
Upvotes: 1
Views: 75
Reputation: 78917
Update II due to concerns of tjebo please see comments: More proper way:
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
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()
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"))
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