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.
source to share
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:
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()
source to share