Business Scenario
You have been asked to create a chart that show sales revenue and gross margin by product line and region. They want the users to be able to use an input control to filter the data by year.
To do this, you decide to add an R visualization to create the custom dual horizontal bar chart with an input control for year in your story using R code.
Task 1: Add an R Visualization Widget to a Story Page
Task Flow: In this practice exercise, you will:
- Investigate the R visualizations in the story
- Add an R visualization widget to the story and configure the dimensions and measures
- Add the initial script to the R visualization
Task 2: Add Scripting to the R Visualization
Task Flow: In this practice exercise, you will:
- Change the line color and fill for the bars in the chart
- Change the orientation of the chart from vertical to horizontal
- Add and configure labels
- Adjust the width of the bars in the chart
- Reorder the regions from smallest to largest values
- Update the labels on the x and y axes
- Change the theme for the chart
Task 3: Add and Configure Product Lines
Task Flow: In this practice exercise, you will:
- Add Lines to the dimensions
- Configure the chart
- Create a stacked bar chart
- Configure the chart title and add a legend
- Scale the Sales Revenue
Task 4: Add and Configure a Second Chart in the R Visualization
Task Flow: In this practice exercise, you will:
- Update the chart to add Gross Margin to the measures
- Add a second chart to the R visualization
- Remove title and subtitle
- Add an input control for Year
Full R Code Used in this Exercise
The final R code in the Editor window of the R visualization script editor is as follows:
1234567891011121314151617181920212223
library(ggplot2)
library(dplyr)
library(grid)
library(gridExtra)
g1 <- ggplot(BestRunCorpRetail, aes(x = reorder(Lines,`Sales Revenue`/1000), y = `Sales Revenue`/1000 , fill = `Region` )) +
geom_col(stat = "identity" ) + coord_flip() +
scale_fill_brewer(palette="Blues") +
labs(title = " Sales Revenue (in k) by Product Line / Region", x = "Product Lines / Region ", y = " Sales Revenue") +
theme_light() +
theme(legend.position="bottom")
g2 <- ggplot(BestRunCorpRetail, aes(x = reorder(Lines,`Gross Margin`/1000), y = `Gross Margin`/1000 , fill = `Region` )) +
geom_col(stat = "identity" ) + coord_flip() +
scale_fill_brewer(palette="Reds") +
labs(title = " Gross Margin (in k) by Product Line / Region", x = "Product Lines / Region ", y = "Gross Margin") +
theme_light() +
theme(legend.position="bottom")
gg1 <- ggplot_gtable(ggplot_build(g1))
gg2 <- ggplot_gtable(ggplot_build(g2))
grid.arrange(gg1, gg2, ncol = 2, widths = c(1/2,1/2))