简体   繁体   中英

plot 2 variables on 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 a lot more rows.

"YEAR" columns range from 2001 to 2013. I have the dataset loaded in data.table "DT"

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

In other words, i have to combine these two graphs in one.

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

I know the way to do it with ggplot2 but couldn't find a way for ggvis. It shall be great even if i could do it in shiny. Your help is highly appreciated.

You can do it this way:

library(ggvis)

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

I assume that you need different colors for each line as well to be able to distinguish the groups so I added the stroke argument.

Output:

在此输入图像描述

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

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

在此输入图像描述

试试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM