2015-06-20 60 views
3

我試圖使用不同數據框中的數據在ggvis圖中添加任意文本的圖例。我曾嘗試使用add_legend(),但我不知道要使用哪些參數。使用plot()是使用legend()功能非常簡單,但它已經很難找到一個方法來做到這一點使用ggvis()ggvis - add_legend具有多個數據和圖內的位置圖例

這裏是我一直在使用plot()一個簡單的例子:

df1 = data.frame(x = sample(1:10), y = sample(1:10)) 
df2 = data.frame(x = 1:10, y = 1:10) 
df3 = data.frame(x = 1:10, y = sqrt(1:10)) 

plot(df1) 
lines(df2$x, df2$y, col = "red") 
lines(df3$x, df3$y, col = "green") 
legend("topleft", c("Data 2","Data 3"), lty = 1, col = c("red","green")) 

現在,使用ggvis()我可以積點,並從不同的數據集的線條,但我不能找到一種方法,使用add_legend()把傳說,這裏是一個使用ggvis()代碼:

df1 %>% ggvis(x=~x,y=~y) %>% layer_points() %>% 
layer_paths(x=~x,y=~y,data = df2, stroke := "red") %>% 
layer_paths(x=~x,y=~y,data = df3, stroke := "green") 

我會很感激任何幫助。

謝謝。

編輯:

這樣僅使用一個數據幀和plot()一個示例代碼

df = data.frame(x = sample(1:10), y = sample(1:10), x2 = 1:10, y2 = 1:10, y3 = sqrt(1:10)) 
plot(df[,c("x","y")]) 
lines(df$x2, df$y2, col = "red") 
lines(df$x2, df$y3, col = "green") 
legend("topleft", c("Data 2","Data 3"), lty = 1, col = c("red","green")) 
+0

我不知道你可以用兩個不同的數據集來做到這一點。儘管從這兩個數據框中構建一個數據框,然後將其融合,那將更有意義。你會得到你想要的這種方式。如果這對你是可以接受的,那麼我可以提供一個解決方案。 – LyzandeR

+0

是的,我可以將所有數據放在一個數據幀中。謝謝。 – Geovany

回答

3

所以,我想出了,是下面的,它的工作原理:

#add an id column for df2 and df3 and then rbind 
df2$id <- 1 
df3$id <- 2 
df4 <- rbind(df2,df3) 
#turn id into a factor 
df4$id <- factor(df4$id) 

#then plot df4 using the stroke=~id argument 
#then plot the legend 
#and finally add df1 with a separate data 
df4 %>% ggvis(x=~x,y=~y,stroke=~id) %>% layer_lines() %>% 
     add_legend('stroke', orient="left") %>% 
     layer_points(x=~x,y=~y,data = df1,stroke:='black') 

它的工作原理:

enter image description here

如果您想傳說移動到情節裏面的位置,那麼你需要試試這個:

df4 %>% ggvis(x=~x,y=~y,stroke=~id) %>% layer_lines() %>% 
    #make sure you use add relative scales 
    add_relative_scales() %>% 
    #values for x and y need to be between 0 and 1 
    #e.g for the x-axis 0 is the at far-most left point and 1 at the far-right 
    add_legend("stroke", title = "Cylinders", 
      properties = legend_props(
       legend = list(
       x = scaled_value("x_rel", 0.1), 
       y = scaled_value("y_rel", 1) 
       ))) %>% 
    layer_points(x=~x,y=~y,data = df1,stroke:='black') 

和輸出:

enter image description here

+0

不客氣!真的很高興我可以幫助:) – LyzandeR

+1

我想看看ggvis文檔上的這種例子。官方網頁(Rstudio)幾乎沒有提供幾個例子。你能推薦我一個更好地瞭解ggvis的好資源嗎?謝謝。 – Geovany

+2

是的,我知道。不幸的是文件仍然很差。這可能是因爲開發人員目前在他們的頭上有很多,但它會變得更好。有一個文檔[here](http://ggvis.rstudio.com/ggvis-basics.html),然後我通常使用'?'。在這個例子中,我只看了'?add_legend',然後嘗試了這些例子並嘗試了很多不同的參數(最初崩潰了很多),直到我理解正確。恐怕還沒有其他來源。 – LyzandeR