Using R scripts in Power BI - Visualization

If you code in R, you have in some cases worked with applications that enable you to use R. One of those that I constantly work with is Power BI. 
There are many visual options available in Power BI including links to custom ones. On the visuals landing tab, you can pick R or Python Scripts as a method to create your desired visual. In this blog, I will demonstrate how to create the visual below (Some have called it a progress bar).



Access you visuals page on Power BI, choose the R script, choose the table columns you need for the visual. Power BI will combine the columns into a data frame called dataset that is available for use. You can rename it data or whatever you decide.

For this case, I have to create the dataset instead of using one from power BI 

Create the data frame and set seed to replicate results

set.seed(5)

data <- data.frame(Facility = c(rep("A",3), rep("B", 3), rep("C",3), rep("D", 3)),

                  Year = rep(c(2021,2022, 2023), 4),

                  Measure = rep(c("measure 1 - a very long measure title", "measure 2", "measure 3"),4),

                  Performance = sample(seq(20:99),12),

                  Lower_target = sample(seq(20:99),12))%>%

  mutate(Upper_target = Lower_target + sample(seq(5:15),12, replace = TRUE))


Prepare the plotting area

mytheme <-theme_void()+ #start with a void theme. Check out other themes here.

  theme(axis.text = element_text(size = 12), #allows you to add/edit/change axis text

      axis.text.y = element_text(hjust = 1),  # right justify axis text especially if it is wrapped

      strip.text = element_blank(),  #remove facet titles

      legend.position = "none")


Visualize the data

data%>%

  filter(Facility == "A")%>%

  mutate(Measure = str_wrap(Measure, 20))%>%

  ggplot(aes(x = Upper_target, 

             y = reorder(Measure, Performance)))+

  geom_col(fill = "#0065A2")+

  geom_col(aes(x = Performance, y = Measure), 

           fill = "#8DD7BF", 

           width = 0.5)+

  facet_grid(rows = vars(Year),

             cols = vars(Facility),

             scales = "free",

             space = "free")+

  geom_errorbar(aes(xmin = Lower_target, xmax = Lower_target), 

                color = '#FC6238', 

                linewidth = 2)+

  geom_text(aes(x = 1, 

                hjust = 0, 

                label = paste0("Rate = ", Performance, "%")))+

  scale_x_continuous(expand = c(0,0.5))+

  mytheme


Note: You can always create a legend to explain your visual with the plot or use textboxes.

Happy reading!

~NMN

Comments

Popular posts from this blog

Financial Mathematics CT-1 Finally Paid Off

Data Scientist Courses (edX vs DatCamp)

Self Joins in R