[R] Secondary y axis in ggplot2: did not respond when change its y-axis value

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri Jan 8 15:58:27 CET 2021


Hello,

What about the following?
First get the min and max of value by variable == "y1".
Then use that range to scale up "y2".

rng <- tapply(daT1$value, daT1$variable, range)$y1

ggplot(data = daT1, aes(x = x, group = variable, color = variable)) +
   geom_line(data = subset(daT1, variable == "y1"),
             aes(y = value)) +
   geom_line(data = subset(daT1, variable == "y2"),
             aes(y = value*diff(rng) + rng[1])) +
   facet_wrap(~group) +
   scale_y_continuous(sec.axis = sec_axis(~ .*0.0001))


Hope this helps,

Rui Barradas

Às 01:01 de 08/01/21, Marna Wagley escreveu:
> Hi R users,
> I was trying to plot a graph with a secondary axis, and used the following
> code for the data but the secondary line and secondary y -axis value did
> not match. I would like to show both lines in one graph.
> 
> Any suggestions?
> 
> library(ggplot2)
> library(reshape2)
> daT<-structure(list(x = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L,
> 3L, 4L, 5L, 6L, 7L, 8L), y1 = c(9754L, 1051L, 5833L, 5769L, 2479L,
> 470L, 5828L, 174L, 2045L, 6099L, 8780L, 8732L, 4053L, 9419L,
> 4728L, 3587L), y2 = c(0.51, 0.61, 0.3, 0.81, 0.89, 0, 1.9, 0.76,
> 0.87, 0.29, 0, 0.42, 0.73, 0.96, 0.62, 0.06), group = c("A",
> "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B",
> "B", "B")), class = "data.frame", row.names = c(NA, -16L))
> print(daT)
> daT1<-melt(daT, id.vars=c("x", "group"))
> daT1%>%
>    ggplot() +
>    geom_line(aes(x = x, y = value, group = variable, color = variable)) +
>    facet_wrap(~group) +
>    scale_y_continuous(sec.axis = sec_axis(~ .*0.0001))
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list