我有一個看起來像這樣謹慎的數據:如何使用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?"
我得到的模板,但沒有得到積分
這些是連續的數據(數字),而不是離散的(類別)。 – Brian
我意識到我鏈接了不正確的來源。如果我使用了錯誤,我已經鏈接了正確的答案並更新了我的答案。 – Ash
在'sec_axis(...)'之前添加'sec.axis ='。沒有明確指定參數,它默認爲'scale_y_continuous()'中的第二個參數,&breaks = sec_axis(〜。* 1.2,name =「height」)'觸發該錯誤,因爲它在上下文中沒有意義。 –