Skip to Content
Technical Articles

Top Bottom Analysis using R Visualizations (part 5)

In part 5, the last of our blog series, we will build a grid of top-n bar charts that allow us to compare countries that consume the most meat by the type of meat eaten and over time.

 

We start by creating a BI Model from a csv file.

The file in question is available here.

 

We save our model and name it MDL_MEAT.

We create a story and insert an R visualization.

We click “Add Input Data” and select the dimensions Country and Year.

 

From the Builder we click on “Add a script” and insert the code shown below to load the packages needed for data manipulation and data plotting.

library(dplyr)
library(tidyr)
library(ggplot2)

Note that this time we use the graphing library ggplot2.

We extract from our dataset the top 5 countries by type of meat eaten and year.

top_limit = 5
df <- MDL_MEAT %>%
   gather(Indicator, Value, -Country, -Year) %>%
   group_by(Indicator, Year) %>%
   mutate(Rank = row_number(-Value)) %>%
   ungroup %>%
   filter(Rank <= top_limit) %>% 
   arrange(Indicator, Year, Value) %>%
   mutate(Sequence = row_number())%>%               
   mutate(header_caption = paste(Indicator, Year)) %>%               
   mutate(header_caption = factor(header_caption, unique(header_caption)))

 

We leverage the facet functionality of ggplot2 to display within a single visualization one bar chart for each combination of meat types and years.

title_caption = paste("Top", top_limit, "meat eating countries by type over 2 decades")
p <- ggplot(data=df, 
            aes(y=Value, x= Sequence)) + 
      geom_bar(stat="identity", width = 0.7, fill="steelblue") + 
	  scale_x_continuous(breaks = df$Sequence, labels = df$Country) +
	  scale_y_continuous(limits=c(0,70)) +
	  coord_flip() + 
      facet_wrap(~header_caption, ncol =3, scales="free") +
	  labs(title = title_caption, y = "Meat Consumption (Kilograms/capita)")
	  
p + theme_bw() +  
    theme(
	panel.border = element_blank()  ,
    plot.title = element_text(color="black", size=16, face="bold", hjust=0.5 ,
	                          margin = margin(t = 0, r = 0, b = 20, l = 0)) ,
	axis.title.x = element_text(size = 12, 
	                            margin = margin(t = 10, r = 0, b = 0, l = 0)) ,
	axis.text.x = element_text(size = 10, face = "bold" , color = "grey",
	                           margin = margin(t = 6, r = 0, b = 0, l = 0)) ,
	axis.ticks.x = element_line(color = "grey") , 
	axis.title.y = element_blank() , 
	axis.text.y = element_text(size = 11, face = "bold", 
	                           margin = margin(t = 0, r = 0, b = 0, l = 0)) ,
	axis.ticks.y = element_blank() ,
	legend.position = "bottom" ,
	legend.text = element_text(size = 14) ,
	strip.background = element_blank() ,
	strip.text = element_text(size = 13, face = "bold") 
   )

 

3 Comments
You must be Logged on to comment or reply to a post.