How to use sec_axis () for discrete data in ggplot2 R?

I have sensitive data that looks like this:

height <- c(1,2,3,4,5,6,7,8)
weight <- c(100,200,300,400,500,600,700,800)
person <- c("Jack","Jim","Jill","Tess","Jack","Jim","Jill","Tess")
set <- c(1,1,1,1,2,2,2,2)
dat <- data.frame(set,person,height,weight)

I am trying to build a graph with the same x axis (person) and two different along the Y axis (weight and height). All examples, I find, are trying to build a secondary axis (sec_axis) or restrained data using basic graphs. Is there an easy way to use sec_axis for discrete data on ggplot2? Edit: Someone in the comments suggested trying this answer. However, I encountered this error now

Here is my current code:

p1 <- ggplot(data = dat, aes(x = person, y = weight)) + 
  geom_point(color = "red") + facet_wrap(~set, scales="free") 
p2 <- p1 + scale_y_continuous("height",sec_axis(~.*1.2, name="height"))
p2

I get the error: Error in x < range[1] : 
  comparison (3) is possible only for atomic and list types

Alternatively, I have now modified the example to fit this example published.

p <- ggplot(dat, aes(x = person))
p <- p + geom_line(aes(y = height, colour = "Height"))

# adding the relative weight data, transformed to match roughly the range of the height
p <- p + geom_line(aes(y = weight/100, colour = "Weight"))

# now adding the secondary axis, following the example in the help file ?scale_y_continuous
# and, very important, reverting the above transformation
p <- p + scale_y_continuous(sec.axis = sec_axis(~.*100, name = "Relative weight [%]"))

# modifying colours and theme options
p <- p + scale_colour_manual(values = c("blue", "red"))
p <- p + labs(y = "Height [inches]",
              x = "Person",
              colour = "Parameter")
p <- p + theme(legend.position = c(0.8, 0.9))+ facet_wrap(~set, scales="free") 
p

I get an error

"geom_path: Each group consists of only one observation. Do you need to 
 adjust the group aesthetic?"

I get a pattern, but no dots are drawn

+4
1

R , . Z.Lin , sec.axis= sec_axis, , sec.axis scale_y_continuous. , scale_y_continuous, breaks=. , , , breaks:

p1 <- ggplot(data = dat, aes(x = person, y = weight)) + 
  geom_point(color = "red") + facet_wrap(~set, scales="free") 
p2 <- p1 + scale_y_continuous("weight", sec.axis = sec_axis(~.*1.2, name="height"))
p2

!  [enter image description here

(name=) of scale_y_continuous y, sec.axis= y. , .

0

Source: https://habr.com/ru/post/1685055/


All Articles