【发布时间】:2018-02-13 04:13:44
【问题描述】:
我有如下所示的谨慎数据:
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 上的离散数据? 编辑: cmets 中有人建议我尝试建议的回复。但是,我现在遇到了这个错误
这是我当前的代码:
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?"
我得到了模板,但没有绘制任何点
【问题讨论】:
-
那些是连续的数据(数字),而不是离散的(类别)。
-
我意识到我链接了错误的来源。如果我使用它,我已经链接了正确的并用错误更新了我的答案
-
在您的
sec_axis(...)前面添加sec.axis =。在没有明确命名参数的情况下,它默认为scale_y_continuous()中的第二个参数,&breaks = sec_axis(~.*1.2, name="height")会触发该错误,因为它在上下文中没有意义。 -
喜欢这个
p1 + scale_y_continuous("height", sec_axis(sec.axis= ~.*1.2, name="height"))?这给我一个错误 -
据我所知
ggplot2不支持独立副轴。所有辅助轴都必须基于主轴的一对一变换。
标签: r ggplot2 axes multiple-axes