我有这样的数据:
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() 绘制多个图形(分面)?
发布评论