2017-09-04 233 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

相關問題