Color control factor group in ggvis-r

I have a question about color control datapoints in ggvis.

I have a dataframe that I filter in several ways (in a brilliant application, if that matters). This leads to the fact that often there are no observations of the groups in which I colorize the data, being present in the resulting filtered frame. This obviously leads to different colors appearing on different graphs that are confusing.

This is a pretty close example:

set.seed(101) dfvis <- data.frame(x = runif(20), y = runif(20), mygroup = LETTERS[1:5]) dfvis dfvis %>% ggvis(x= ~x, y= ~y) %>% layer_points(fill = ~factor(mygroup)) 

enter image description here

Filter out group -

  dfvis <- dfvis %>% filter(mygroup!="A") dfvis %>% ggvis(x= ~x, y= ~y) %>% layer_points(fill = ~factor(mygroup)) 

enter image description here

Here, “B” is now blue, and all other groups are shifted by one in terms of color order.

Is there a way when multiple filters on the same df always provide the same color for each factor / group level?

One trick that previously worked in ggplot was to add one NA observation at the end of the data frame for each factor level. At first glance, this works fine when the colors returned in the correct order, but pay attention to the rogue data point in the upper left!

 dfvis1 <- rbind(dfvis, data.frame(x=NA, y=NA, mygroup="A")) dfvis1 %>% ggvis(x= ~x, y= ~y) %>% layer_points(fill = ~factor(mygroup)) 

enter image description here

all help is appreciated.

+7
r ggvis
source share
1 answer

Solution 1

I seem to have missed a very simple solution:

Just redefine the factor levels and uncheck the coefficient with fill=

I will leave it as it may help someone else.

 dfvis$mygroup<-factor(dfvis$mygroup, levels=c("A", "B", "C", "D", "E")) dfvis %>% ggvis(x= ~x, y= ~y) %>% layer_points(fill = ~mygroup) 

Decision 2

This can be more general for ggvis users. We can use : compared to := . Create a new color variable for each group.

 dfvis$color <- c("blue","orange","green","red","purple") 

Then we can use the unscaled source color value with fill:= inside the ggvis function ...

 #:= denotes unscaled raw value dfvis %>% ggvis(x= ~x, y= ~y, fill:= ~color) %>% layer_points() 

This will ensure color consistency even after filtering other groups.

+9
source share

All Articles