2015-06-20 49 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