Plot 2 variables on the Y axis using ggvis in R

I have a dataset that looks like this:

"YEAR","A","B"
2001,100,177 
2002,154,419 
2003,334,190
2012,301,90

      

.. and many more lines.

Graphs

"YEAR" ranges from 2001 to 2013. I have a dataset loaded into the data.table "DT"

I want to plot a graph with YEAR on the X axis and line graphs for A and B on the Y axis.

In other words, I need to combine these two graphs into one.

DT %>% ggvis(~YEAR, ~A) %>% layer_lines()
DT %>% ggvis(~YEAR, ~B) %>% layer_lines()

      

I know a way to do this using ggplot2, but couldn't find a way for ggvis. It will be great even if I can make it brilliant. Your help is greatly appreciated.

+3


source to share


2 answers


You can do it like this:

library(ggvis)

DT %>% ggvis(x= ~YEAR) %>%
  layer_lines(y= ~A, stroke:='blue')   %>%
  layer_lines(y= ~B, stroke:='orange')

      

I am assuming that you need different colors for each row to be able to distinguish between groups, so I added an argument stroke

.

Output:



enter image description here

It would probably be even better if you melt the data.frame first and then draw with a hit argument which will return the legend as well. Like this:

library(reshape2)
DT2 <- melt(DT, 'YEAR', c('A','B'))
DT2 %>% ggvis(~YEAR, ~value, stroke=~variable) %>% layer_lines()

      

enter image description here

+3


source


Try the following:



DT %>% ggvis(~YEAR, ~A) %>% layer_lines()%>%layer_lines(x=~YEAR, y=~B)

      

+2


source







All Articles