Search code examples
rshinyggvis

eliminate unused factor values in ggvis Shiny


I want to eliminate not used factor value from x-axis in ggvis plot. I have data.frame

choices <- c("Value1", "Value2",
                "Value3", "Value4",
                "Value5", "Value6",
                "Value7", "Value8",
                "Value9", "Value10",
                "Value11", "Value12")

levele <- c("AT1","AT2","AT3","AT4","AT5","RT1","AT6","AT7","AT8","AT9","AT10","RT2")

number_value1 <- sample(1:100,22)
number_value2 <- sample(1:100,22)

df1 <- data.frame(product = c(rep("Product1",12),rep("Product2",10)), name = c(choices,choices[1:10]),
                  short_name = c(levele,levele[1:10]),number = number_value1, number2 = number_value2) 

and when I want to create a ggvis only with data based on Product2 I get

df1 %>%
  dplyr::filter(product == "Product2") %>%
  ggvis(x = ~short_name,y =  ~number) %>%
  layer_points(size := 120,fill = ~short_name)

enter image description here

Plot shows also unused factor values. I do not want to see that so I used x = ~factor(short_name) to eliminate these unused cases.

df1 %>%
  dplyr::filter(product == "Product2") %>%
  ggvis(x = ~short_name,y =  ~number) %>%
  layer_points(size := 120,fill = ~short_name)

enter image description here

====================================================================
So that's fine. The problem is when I want to do it the same thing in Shiny app, which has possibility to manipulate axis. There are 2 dataframes in which there are 2 Products with different number of name. When I change Product1 to Produt2 in Select Product section in result I have all factors in x-axis, also unused factors. My code is here. If anyone knows how to implement it correctly?


Solution

  • As @docendo discimus pointed out, you can use droplevels. I forked your code and made the changes here