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

标签 r ggplot2 axes 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)

我正在尝试绘制具有相同 x 轴(人)和 2 个不同 y 轴(重量和高度)的图形。我发现所有的例子都试图绘制 secondary axis (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

或者,现在我修改了示例以匹配 this example posted.
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

我收到一个错误提示
"geom_path: Each group consists of only one observation. Do you need to 
 adjust the group aesthetic?"

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

最佳答案

如果未明确指定参数名称,则 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= 的第一个参数 ( scale_y_continuous )用于第一个 y 比例,其中 sec.axis=参数是针对第二个 y 尺度的。我更改了您的第一个 y 比例名称以纠正该问题。

关于r - 如何将 sec_axis() 用于 ggplot2 R 中的离散数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46045258/

相关文章:

r - 设置数组中矩阵的行名称

r - 在多个页面上使用 grid.arrange 或带有 layout_matrix 的 marrangeGrob

r - 标记绘图区域外的线尾

r - 如何将 x 和 y 轴的截距放置在 (0 , 0) 并将 x 和 y 轴延伸到绘图的边缘

python - matplotlib: AttributeError: 'AxesSubplot' 对象没有属性 'add_axes'

r - 在 Shiny 中更新子集数据表

r - R 中的错​​误 : could not find function . ..

r - read_csv() 使用随机数做什么?

r - 使 geom_text 颜色比 geom_point 颜色深

python - 如何在 Bokeh 中完成 `set_xlim` 或 `set_ylim` ?