2017-09-04 232 views
4

我有一个看起来像这样谨慎的数据:如何使用sec_axis()来处理ggplot2 R中的离散数据?

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?" 

我得到的模板,但没有得到积分

+0

这些是连续的数据(数字),而不是离散的(类别)。 – Brian

+0

我意识到我链接了不正确的来源。如果我使用了错误,我已经链接了正确的答案并更新了我的答案。 – Ash

+0

在'sec_axis(...)'之前添加'sec.axis ='。没有明确指定参数,它默认为'scale_y_continuous()'中的第二个参数,&breaks = sec_axis(〜。* 1.2,name =“height”)'触发该错误,因为它在上下文中没有意义。 –

回答

0

如果未明确指定参数名称,则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的比例。我改变了你的第一个比例尺名称以纠正它。

+0

但是这似乎并没有绘制出重量和身高。我需要将重量和高度都绘制在相同的x轴上。 – Ash

+0

@Ash这只是没有正确指定的标签。看到我编辑的答案。 – useR

+0

不,我认为你看不到我的观点。对于每个人,例如。在Set1中,对于Jack,我应该看到两个点,一个对应于他的身高(用红色表示),另一个对应于他的体重(标记为黑色)。这里的情节反而会产生一个点,也许是体重和身高之间的关系?这不是我想要的。 – Ash

相关问题