如何在ggplot2 R中将sec_axis()用于离散数据?

Ash*_*Ash 5 r axes ggplot2 multiple-axes

我有一些谨慎的数据,如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

我正在尝试绘制具有相同x轴(人)和2个不同y轴(体重和身高)的图表。我发现所有示例都试图使用基准图绘制辅助轴(sec_axis)或谨慎的数据。有没有一种简单的方法可以将sec_axis用于ggplot2上的离散数据?编辑:评论中有人建议我尝试建议的答复。但是,我现在遇到这个错误

这是我当前的代码:

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
Run Code Online (Sandbox Code Playgroud)

或者,现在我修改了示例以匹配发布的示例。

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
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:

"geom_path: Each group consists of only one observation. Do you need to 
 adjust the group aesthetic?"
Run Code Online (Sandbox Code Playgroud)

我得到了模板,但没有点被绘制

avi*_*seR 0

如果未明确指定参数名称,则 R 函数参数按位置输入。正如 @Z.Lin 在评论中提到的,您需要在函数sec.axis=之前sec_axis表明您正在将此函数输入到 的参数sec.axisscale_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
Run Code Online (Sandbox Code Playgroud)

![在此输入图像描述

第一个参数 ( name=)scale_y_continuous用于第一个y 尺度,而 assec.axis=参数用于第二个y 尺度。我更改了你的第一个 y 刻度名称来纠正这个问题。

  • @Ash 我明白了,你实际上想要在同一个图上有两个不同的 y 轴。在这种情况下,“sec.axis”不是正确的解决方案,因为它只允许第二个轴是第一个轴的线性变换。我认为“ggplot2”没有好的解决方案,因为它的设计目的是阻止数据的误传。请参阅此讨论:/sf/ask/216945361/正确的 (2认同)