如何在 R 中使用 twoord.plot() 绘制多个图形(分面)?

编程入门 行业动态 更新时间:2024-10-11 11:17:52
本文介绍了如何在 R 中使用 twoord.plot() 绘制多个图形(分面)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这样的数据:

height <- c(1,2,3,4,2,4,6,8) weight <- c(12,13,14,15,22,23,24,25) 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)

我正在尝试使用 plotrix 中的 twoord.plot 函数绘制具有相同 x 轴(人)和 2 个不同 y 轴(重量和高度)的图形 包.但是,我不知道如何像 ggplot2 那样对情节进行分面.

I'm trying to plot a graph with same x-axis(person), and 2 different y-axis (weight and height) using the twoord.plot function from the plotrix package. However, I do not know how to facet the plots like in ggplot2.

例如,如果我的图可以在 ggplot2 中叠加,我的代码将如下所示:

For example, if my plots could overlay in ggplot2, my code would look something like this:

ggplot(data = dat, aes(x = person, y = weight)) + geom_point(color = "red") + facet_wrap(~set, scales="free") #And similarly have the height on the other axis.

知道如何在 twoord.plot() 中实现这一点吗?

Any idea on how to achieve this in twoord.plot()?

推荐答案

我觉得这个情节真的很混乱,但这似乎或多或少是 plotrix::twoord.plot 所做的,所以让我知道这是否是你的想法.

I find this plot really confusing, but this seems to be more or less what plotrix::twoord.plot does, so let me know if this is what you had in mind.

在 ggplot2 中,第二个轴必须基于第一个轴的变换.因此,我们首先转换绘制的高度值,将它们置于与权重值相同的范围内(因此它们将出现在基于权重的图表的 y 范围内).然后我们对第二个 y 轴的比例进行逆变换(这样 y 轴比例将对应于数据中的实际高度值).

In ggplot2, a second axis has to be based on a transformation of the first axis. So, we first transform the plotted height values to put them within the same range as the weight values (so they'll appear within the y-range of a graph based on weight). Then we do the inverse transformation to the scale of the second y-axis (so that the y-axis scale will correspond to the actual height values in the data).

ggplot(dat, aes(person)) + geom_point(aes(y=weight), colour="blue") + geom_point(aes(y=height/mean(height/weight)), colour="red", shape=17) + scale_y_continuous(sec.axis=sec_axis(~ . * mean(dat$height/dat$weight), breaks=seq(0,max(dat$height),1), name="height")) + theme_classic() + theme(axis.text.y.right=element_text(colour="red"), axis.text.y=element_text(colour="blue"), axis.title.y.right=element_text(colour="red"), axis.title.y=element_text(colour="blue"))

这对我来说似乎更直观,特别是如果每​​个人的测量值(隐式)按时间排序:

This seems more intuitive to me, especially if the measurements of each person are (implicitly) ordered in time:

ggplot(dat, aes(weight, height, label=person, group=person)) + geom_line(colour="grey70") + geom_text()

更多推荐

如何在 R 中使用 twoord.plot() 绘制多个图形(分面)?

本文发布于:2023-07-18 14:17:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145633.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   图形   如何在   plot   twoord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!