Tag: Dax

  • Temple of DAX – 3D

    Temple of DAX – 3D

    To celebrate joining the Power BI Cat team next week, I thought I would update a DAX game I built last November (2018) which was a DAX-based maze game in Power BI that allowed you to navigate a character through a series of user-created maps in a top-down view.

    The details for that game are in this blog posting. http://radacad.com/fun-with-dax-a-maze-ing-dax.

    The update I wanted to make was to see what is involved in creating a 3D, first-person version of the same maze.  The following is how I got on.

    The PBIX File for the Temple of DAX – 3D can be downloaded using this link and here is a link to the publish to web version.

     

    Like the 2D version, the report imports a CSV file which it uses to generate the map.  I pretty much used exactly the same code to import the CSV file and pivot the coordinates to a format for suitable for processing in DAX.

    All you need to create/edit your own custom maps is to open and edit a CSV file using your preferred editor and place an X character where you would like a wall to be and an I character for the insight (or exit).  Excel is great for this particular task as you can size and align the columns nicely to easily see where walls will be.

    The following image shows the data1.csv file opened in MS Excel, with all columns set to the same width of 15-pixels.  Once modifications are complete, save the file as CSV (not xlsx) in the folder the PBIX file uses to import from.

    Once again, I’d like to thank Margarida Prozil for providing a custom control to manage the navigation.  This is an updated version of the D-PAD called a 3D-Pad.  You can grab a copy from her GitHub repo if you are keen to work with this control.

    https://github.com/mprozil/dPad-3D/tree/master/dist

    The control has four arrows.  The Up/Down arrows move you back and forward through the map, while the left/right arrows spin you 45 degrees.  This is different behaviour to the D-Pad in the 2D version of the maze.

    I’d also like to thank Mike Carlo at PowerBI.Tips for providing the wonderful background image and the overall visual design of the game.  It was Mikes idea for the evil laugh on the intro page.  This started to drive me a bit nutty as it would play everytime I saved the file.

    The Game Logic

    Like the 2D game, this version uses SVG as the method to draw the graphics to the screen.  Each time an arrow is clicked, a new view needs to be generated based on the interaction, so a calculated measure takes into account the new position or perspective and generates a fresh SVG to be displayed using the Image control by CloudScope.

    The SVG image displayed in the Image Control is a nested set of mini SVG polygons that draw the outline of various shapes into an outer SVG file.  The performance is pretty good and I have still yet to hit any limitations on text size to store the final SVG set.

    The 3D world

    The first challenge was to figure out how to convert coordinates in a table in the data model into an image that looks like you are walking through a maze.

    The map I use in the uploaded PBIX file is 26 steps and 36 steps long, so it isn’t big.  If a step has been designated as a wall, it effectively has 4 walls (panels) around its perimeter, and when a series of X values in the CSV run next to each other, a longer wall effect is created.

    Each of the panels for a step in the board has 5 points.  I initially created these panels as 100 x 100 walls, but I found it added the extra point at the top to help me work out which way was up when I was first playing with the 3D to 2D projection code.

    The Calculated table called 3D Worlds takes the basic X/Y coordinates from the CSV file and generates a 3D world of X/Y/Z points for every panel on every all in the maze.

    The image below shows all X/Y/Z coordinates for 1 step in the CSV map.  The first column shows there are four panels.  Think of these as like north, east, south and a west facing wall.  Each wall as five points.  These five points define each corner of the wall in terms of a 3D world and the X, Y and Z columns for each row specify exactly where each point should be in a three-dimensional plane.

    3D to 2D projection

    The next challenge is to take the 3D coordinates and convert this information into an image that represents what you should see based on your location in the map, along with the direction you are looking.  There was no way I was going to figure the maths for this out from scratch, and after a few internet searches and a bit of reading, I found this article to have all the information I needed.

    https://en.wikipedia.org/wiki/3D_projection

    The key information is in the section on Perspective Projection, including the algorithm I ported into the DAX measure in the game.

    The basic principle is to define a 2D plane (or screen) called a viewport that sits a specific distance from the eyeball. Then an imaginary line is calculated between the eyeball and every X/Y/Z point from the 3D World table.  If any of these lines pass through the viewport, they can be plotted onto the viewport at a specific 2D x/Y coordinate.

    The code I used from the Wikipedia article is the following:

    The Main Map calculated measure contains all the DAX code to convert the 3D data points to 2D coordinates using SVG.

    The section of code in the Map Map calculation that matches first the algorithm from the Wikipedia article is here :

    I’m not going to pretend to understand this any more than it reminds me of math classes from when I was 15, working out SIN, COSINE equations.  I swore then I would never use them for real, so I guess I owe my old maths teacher an apology.

    The good news is I didn’t need to understand the code in the end.  Once I’d added it to the DAX calculated measure and started generating SVG polygons, it’s quickly looked the way I wanted.

    I probably spent less than 2 hours getting this aspect of the game to work.  There was a little fine-tuning while I worked out what the various elements were, but this was much easier than I anticipated.

    A nested set of CONCATENATEX functions in the Main Map calculated column, loop through every object defined in the 3D World table and converts points to 2D versions.  A series of filters are applied to stop plotting any graphics that fall outside the 2D viewport, such as walls that are behind you (taking into account the direction you are looking).

    The objects are drawn from furthest to nearest to make sure far away objects do not appear if they are covered by a nearer object.  This also means portions of further away objects will appear as expected if they can be partially seen.

    Other filters are applied to stop panels of walls being plotted when they simply cannot be seen.

    Mini Map

    A separate Mini Map calculated measure generates a non-3D version of the map and gets added to a separate Image Viewer custom control to show your position in the map.  A small red triangle shows your position and direction and a small white square shows the exit.  In this case, it’s inside the letter E.

    3D Dpad

    Margarida Prozil supplied me with an updated 3D control that sits on the top of three separate columns in the database.  X and Y (rows and columns) control the square you currently occupy, while the third column is V (for view perspective).  X and Y represent how many squares wide, or long the map is.  V represents the angle in steps of 45 degrees and there are 8 possible values (0, 45, 90, 135, 180, 225, 270  and 315).  The example map is 26 squares wide, 36 squares long so combined with the 8 views, mean the control can be set to 7,488 possible values.  A custom control can only manage about 30,000 points, so take this into account for larger custom maps.

    Summary

    I’m pretty happy with the 3D effect and can see it can be used with other X/Y/Z based 3D coordinates plotted to a 2D view plane.  When I was debugging this, I had slicers for height on the screen so I could use a slider to create an effect of flying up in the air – and the maze still rendered as expected.  Power BI seems to cope with the workload pretty well, despite not really optimised for this kind of work.  In future versions, I may add more objects and detail to push the engine harder and see where breaking points are.

    There probably aren’t too many business use-cases in Power BI for this type of report aside from educational.  Feel free to have a look through the PBIX file where you may pick up some useful ideas, tips and tricks in the DAX.

    There is a small bug at the start of the game when the bookmark drops you into the maze and you need to click the up arrow a few times to get going.  Once you are on your way, it’s pretty good.  I’ll try to get that resolved in the next few days.

     

     

     

  • UseRelationship DAX Tutorial – Curbal

    UseRelationship DAX Tutorial – Curbal

    Here is another great tutorial from Curbal.  This tutorial teaches you how to use the DAX function UserRelationship.  This is important when your dealing with a tables in your data model that have multiple relationships.  Power BI by design can only handle one relationship between two different tables.  This will also be an important function to use when you have source tables that contain multiple date columns.  This is a pretty slick function when handling supply chain type data sets.

    For the full documentation from Microsoft visit this page.

    The Highlights:

    Full video below:

    Curbal has been generating a lot of great content.  To learn about for more information you can visit the website found here, or visit the YouTube Channel.

    For more great videos about Power BI click the image below:

    PBI Videos

     

  • SUM & SUMX Tutorial – Curbal

    SUM & SUMX Tutorial – Curbal

    Learn how to use SUM() and SUMX() with this great video from Curbal. As you become more familiar with PowerBI you will increase your understanding of DAX (Database Analysis Expressions). Microsoft has an extensive list of all the expressions you can use found here.  One of the more common expressions you will use is SUM and SUMX.

    Example of SUM, SUMX and Calculate from PowerPivotPro

    Microsoft Documentation of SUM

    Microsoft Documentation of SUMX

    Using the SUMX and SUM expressions:

    To learn more about DAX I have read both of these book and found them extremely helpful.  They both cover the basics and then quickly get you understand how to make complex calculations which you will need to make the right visual work.

    Curbal has been generating a lot of great content.  To learn about for more information you can visit the website found here, or visit the YouTube Channel.

    For more great videos about Power BI click the image below:

    PBI Videos

  • Pareto Charting in PowerBI

    Pareto Charting in PowerBI

    The Pareto chart is a handy visual, but is not so easy to build in either excel or PowerBI.  In a Pareto chart, information is provided about an individual product or category as a bar, and a cumulative scale as a line which compairs all bars.  This type of visual can be extremely helpful when conducting failure mode analysis, causes of a problem, or even product portfolio balances.  For some more information on Pareto charts you can learn more here or here.  If you’re interested in building a Pareto chart in excel, I have found this post from Excel Easy to be helpful.

    To give you a little teaser of what we will be building today, below you will see an image of the final Pareto chart.  On the left side we have sales of units, and on the right is the cumulative percent of all sales.  Using the Pareto chart a user has the ability to see which products comprise the majority of your sales.  For example, the first 4 bars total approximately 50% of all sales.

    Pareto Final Product
    Pareto Final Product

    Alright, let’s get started.

    Open up PowerBI Desktop, Click the Get Data button on the Home ribbon and select Blank Query.  Click Connect to open the Query Editor.  Click Advanced Editor on the View ribbon.  While in the Advanced Editor paste the following code into the editor window.

    Note: If you need some more help loading the data follow this tutorial about loading data using the Advanced Query Editor.  This tutorial teaches you how to copy and paste M code into the Advanced Editor.

    let
     Source = Excel.Workbook(Web.Contents("https://powerbitips03.blob.core.windows.net/blobpowerbitips03/wp-content/uploads/2016/10/Sample-Data.xlsx"), null, true),
     Table1_Table = Source{[Item="Table1",Kind="Table"]}[Data],
     #"Changed Type" = Table.TransformColumnTypes(Table1_Table,{{"Item", type text}, {"Sales", Int64.Type}, {"Segment", type text}})
    in
     #"Changed Type"

    Rename the Query to Data.  Once you’ve completed the data load your data should look like the following.

    Load Data to Query Editor
    Load Data to Query Editor

    On the Home ribbon click Close & Apply to complete the data load.

    Close and Apply
    Close and Apply

    Let’s begin with a little exploration of our data.

    Pro Tip: When I am building reports I often load the data and then immediately start building a couple of tables and slicers.  It helps me understand how my data reacts to the slicers and helps me determine how to shape the data so that the visuals will work properly.  For this example, we only have one table, but when loading data things can get rather complex due to loading multiple tables with multiple relationships.

    Add a Slicer for the Segment.  Enhance the look of the slicer by changing it from a vertical to a horizontal slicer.  While the slicer is highlighted, click the Paint Roller expand the General section and change the orientation from vertical to Horizontal.

    Segment Slicer
    Segment Slicer

    Repeat the same process to add a Slicer for the item field.

    Item Slicer
    Item Slicer

    Next, add a table view of all the fields.  Start with Segment, then Item and finally add Sales to the Table Visual.

    Data Table
    Data Table

    Notice, now that we added all the Fields, there are a number of repeating values.  We have Category 1 and Item 1 repeated 9 times.  In some cases, it will be necessary to have this level of data brought into the data model within PowerBI.  A common reason is that this level of granularity is required for other report pages, or visuals.  It is OK to bring large amounts of data, but as a method of best practice it is recommended that you bring in the data required to support the visuals.

    Now, to address these multiple items that we see in our data.  In the sample Pareto image provided at the beginning of this Tutorial we only had one bar for Category 2 Item 3.  Thus, we need to summarize each grouping of every Category and Item combination.  To do this we will construct a summary table.

    First, we will create a unique Key that will be used to summarize each combination of Category and Item pair.  Click the bottom half of the New Measure button located on the Home ribbon.

    Calculated Column
    Calculated Column

    Enter the following DAX expression.  This new column titled Blend will be the unique Key that is utilized to summarize the data.

    Blend = Data[Segment]  &  "-"  &  Data[Item]

    Select the Modeling ribbon and then click on the New Table button.  Enter the following DAX expression.

    Summary = SUMMARIZE('Data', Data[Blend], "Sum Sales", SUM(Data[Sales]) )

    For more information on the SUMMARIZE function you can visit the Mircosoft Summarize documentation page.  In this equation we first select the table and in this case it is ‘Data’.  Then the column we want to summarize or group by is the Segment column noted as Data[Blend].  The next field is the title of the summarized field column, noted as “Sum Sales”.  Then DAX function that calculates the Sum of the column labeled Data[Sales], noted as SUM(Data[Sales]).  It is relevant to point out here that the SUMMARIZE function will only work with building a new table and not as a calculated column or measure.

    Add a new Table visual to the report and include the two newly created fields from the Summary table.

    Summary Table Visual
    Summary Table Visual

    We have a field titled Blend which is our Key for all the summarized groupings.  Next, we will want to parse out the Segments and Items from this blend column.  We will want to use Category 1 & 2 in a slicer and the same for Items 1 to 5.  Highlight the summary table by clicking the grey space next to the word Summary.  Click the New Column button on the Modeling ribbon and enter the following DAX expression.

    Segment = PATHITEM(
       SUBSTITUTE(Summary[Blend], "-" , "|" ),
       1 )

    In this expression the Substitute function replaced the dash “-” with a “|” character.  Then the PATHITEM function can then parse the text into segments.  By entering a 1 we select the first item in the sequence.  For our example we only have two items, but when you’re working with file paths you can have multiple items in the path such as “\users\mike\my documents\my folder\”, which would equate to users = position 1, mike = position 2, my documents = position 3, etc..

    Add another new column with the following DAX expression for the item column.

    Item = PATHITEM( 
      SUBSTITUTE(Summary[Blend], "-" , "|" ),
      2 )

    Note: We changed the PATHITEM position from 1 to 2.

    Next add the newly created Segment and Item columns to our summary table visual that we created earlier.

    Add New Fields
    Add New Fields

    Nice job so far.  Now we have to modify our slicers to point to the new Item and Segment fields we created in the Summary table.  Select the Segment Slicer Visual and add the Segment Field from the Summary table.

    Update Segment Slicer
    Update Segment Slicer
    Update Item Slicer
    Update Item Slicer

    Now that we have updated the slicers, we can now can control the table visual made from the Summary table.

    Select Category 1 and Items 1 to 3
    Select Category 1 and Items 1 to 3

    Pro Tip: To select multiple items in a slicer you can hold down the Ctrl button on the key board and click multiple slicer items.  This is how I was able to select Items 1 to 3.

    Now we are ready to build the measures that will support the Pareto chart.  Click on the bottom half of the New Measure button on the Home ribbon and select New Column.  Add the following DAX expression to rank all the items in the Summary table.

    Ranking = RANKX(  'Summary',   'Summary'[Sum Sales])

    Add a measure for the Cumulative total according to the new ranking column we created.  Click the top half of the New Measure button on the Home ribbon.  Add the following DAX expression.

    Cumulative Total = CALCULATE(
        SUM( Summary[Sum Sales] ),
        FILTER( ALLSELECTED( Summary ),
            Summary[Ranking] <= MAX( Summary[Ranking] )
        ))

    Repeat the add measure process and add a Total measure which will total only the items from the summary table that have been selected in the report view.  Add the following DAX expression.

    Total Sales = CALCULATE(
     SUM( Summary[Sum Sales] ) ,
     ALLSELECTED( Summary )
     )

    For the last measure, repeat the process to add another measure.  Enter the following DAX expression as a measure.

    Cumulative Percent = [Cumulative Total] / [Total Sales]

    The Cumulative Percent measure is a calculated as a percentage, thus we need to change this measure’s formatting to percentage.  Click the measure labeled Cumulative Percent then change the Format to Percentage which is found on the Modeling ribbon.

    Change Formatting
    Change Formatting

    Your Summary table should now look like the following.

    Updated Fields List
    Updated Fields List

    To see all the calculations that we just created add all the fields from the Summary table to the Summary table visual we created earlier.

    Full Summary Table Visual
    Full Summary Table Visual

    At last, we are ready to add the Pareto chart.  Add the following fields to the line and stacked column chart.

    Add Line and Stacked Bar Chart
    Add Line and Stacked Bar Chart

    Order the data in descending order by the number of sales by click the visual’s Ellipsis and selecting Sort By Sum Sales.

    Sort by Sales
    Sort by Sales

    This changes the order of the items to make a Pareto chart.

    Final Pareto Chart
    Final Pareto Chart

    Thanks for following along.  Share if you enjoyed this tutorial.

  • Make Calendars Using DAX – Curbal

    Make Calendars Using DAX – Curbal

    Often you will need to create some custom calendars within your PowerBI reports.  Ruth Pozuelo from Curbal does a great video tutorial on using Calendar() and CalendarAuto().  I have use the Calendar() DAX function many times and find it very helpful.  The following videos are built directly within DAX.  This approach is one of many different methods that can be used to generate a list of dates.  In a previous tutorial I talked about how to build a date table within the Query Editor (build date table in the Query Editor).

    One method that Ruth talks about is the ability to use the CalendarAuto().  I have not used this expression in any previous reports, but seeing how simple it is to implement this will definitely have to be added to the toolbox.

    Microsoft Docs on Calendar()

    See Calendar DAX example below:

    = CALENDAR (DATE (2005, 1, 1), DATE (2015, 12, 31))

    Microsoft Docs on CalendarAuto()

    See CalendarAuto DAX Example below:

    = CALENDARAUTO()

    Here are the highlights from Ruth’s video:

    Using Calendar:

    Using CalendarAuto:

    Full Video:

    Curbal has been generating a lot of great content.  To learn about for more information you can visit the website found here, or visit the YouTube Channel.

    For more great videos about Power BI click the image below:

    PBI Videos

  • Measures – Intelligent Card Visual – Using DAX

    Measures – Intelligent Card Visual – Using DAX

    As I have been exploring PowerBI and building dashboards I have noticed that often the visuals can obscure your data.  As you click on different visuals there is a need to highlight different pieces of data.  Take for example the following dashboard:

    Sample Visual Example
    Sample Visual Example

    Notice the different car types in the bar chart.  As you click on each vehicle type, Diesel, Hatchback, etc.. you expect the data to change accordingly.  In some cases it is helpful to present a card visual to show the user what you selected and any relevant data points you want to highlight.  For example if I select the Diesel vehicle type I may want to know the average sales amount, total sales in dollars, or number of units sold.  This is where we can build specific measures that will intelligently highlight selected data within your PowerBI visual.

    Here is a sample of what we will be building today:

    lets begin with starting with some data.  In honor of your news feed being bombarded with Pokemon Go articles lets enter some data on Pokemon characters.

    We will enter our data manually.  For a full tutorial on manually entering in data visit here.

    Click the Enter Data button on the Home ribbon and enter the following information into the displayed table.

    Pokemon XP
    Pikachu 1200
    Weedle 650
    Pidgey 800
    Golbat 300

    Rename the table to Characters.  Once you are finished entering in the data it should look like the following:

    Create Table of Characters
    Create Table of Characters

    Click Load to continue.

    Start to examine your data by building a table visual.

    Table Visual
    Table Visual

    Next add a Bar chart.

    Bar Chart
    Bar Chart

    Note: I added the XP column twice.  Once to the Value attribute and to the Color Saturation.  This enhances the look of your visual by coloring the bars with a gradient.  The largest bar will have the darkest color, and the smallest bar will have the lightest color.

    Next, we will begin building some measures.  The first measure will be a total of all the experience points (XP) for each character. Click the New Measure button on the Home ribbon and enter the following DAX expression:

    Total XP = Sum(Characters[XP])

    Now, add a Card visual and add the new measure we created Total XP.

    Total XP Card Visual
    Total XP Card Visual

    This measure totals all the experience points for all the selected characters within the visual.  Since all characters are now selected the total XP for all characters is 2,950.

    The next, and final measure, will be the intelligent card.  For this measure we want to display the characters name when we select them in the bar chart.  Click the New Measure button on the Home ribbon and enter the following DAX expression:

    Character(s) = IF( DISTINCTCOUNT(Characters[Pokemon]) = 1 , FIRSTNONBLANK('Characters'[Pokemon],'Characters'[Pokemon]) , DISTINCTCOUNT('Characters'[Pokemon]) & " Selected")

    Update: As of Mid 2017 Microsoft introduced a new DAX expression called SELECTEDVALUE which greatly simplifies this equation.  Below is an example of how you would change the DAX equation to use SELECTEDVALUE.

    Selected = SELECTEDVALUE(  Characters[Pokemon],  DISTINCTCOUNT(  Characters[Pokemon]  )  &  " Selected" )

    Explanation of this measure:

    This measure first checks to see how many distinct items are in the column Pokemon of our dataset.  If there is only one selected character then we will display the FIRSTNONBLANK character, which will be the name of our selected character.  If there are more than one characters selected. The measure will count the number of characters selected and return a text string with the count and the word SelectedThus, showing us how many items have been selected.

    Add the measure titled Character(s) to a card visual.

    Add Character Card Visual
    Add Character Card Visual

    We can now see that there are 4 characters selected.  Clicking on Pikachu in the bar chart resolves with the character’s name being displayed and the XP of Pikachu being displayed in the Total XP card visual.

    Selecting Pikachu
    Selecting Pikachu

    You can select multiple items by holding down Ctrl and clicking multiple items in the bar chart.

    Selecting Pikachu and Pidgey

    Well, that is it.  I hope you enjoyed this Pokemon themed tutorial.  Thanks for visiting.

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

  • Measures – Dynamic Percent Change – Using DAX

    Measures – Dynamic Percent Change – Using DAX

    This tutorial will produce a measure that will dynamically calculate a percent change every time an item is selected in a visual.  The previous tutorial can be found here.  In the previous tutorial we calculated the percent change between two time periods, 2014 and 2013.  In practice it is not always desirable to force your measure to only look at two time periods.  Rather it would be nice that your measure calculations change with changes in your selections on visuals.  Thus, for this tutorial we will add some dynamic intelligence to the measures. Below is an example of what we will be building:

    First here is the data we will be using.  This data is the same data source as used in the previous % change tutorial.  To make things easy I’ll give you the M code used to generate this query.  Name this query Auto Production.

    let
     Source = Web.Page(Web.Contents("https://en.wikipedia.org/wiki/Automotive_industry")),
     Data0 = Source{0}[Data],
     #"Removed Columns" = Table.RemoveColumns(Data0,{"Change", "Source"}),
     #"Changed Type" = Table.TransformColumnTypes(#"Removed Columns",{{"Production", Int64.Type}, {"Year", Int64.Type}})
    in
     #"Changed Type"

    Note: the code shown above should be added as a blank query into the query editor.  Add the code using the Advanced Editor.  Another tutorial showing you how to add advanced editor code is here

    Once you’ve loaded the query called Auto Production.  The Field list should look like the following:

    Production
    Auto Production

    Next add a Table with Production and Year.  this will allow us to see the data we are working with.  When you initially make the table the Year and Production columns are automatically summed, thus why there is one number under year and production.

    Table of Data
    Table of Data

    Rather we want to see every year and the production values for each of those years.  To change this view click on the triangle in the Values section of the Visualizations pane.  This will reveal a list, in this list it shows that our numbers are aggregated by Sum change this to Don’t Summarize.

    Change to Don't Summarize
    Change to Don’t Summarize

    Now we have a nice list of yearly production levels with a total production at the bottom of our table.

    Table of Production Values by Year
    Table of Production Values by Year

    Next we will build our measure using DAX to calculate the percent changes by year.  Our Calculation for % change is the following:

    % Change  =  ( New Value / Old Value ) - 1

    Below is the DAX statement we use as our measure.  Copy the below statement into a new measure.

    % Change = 
    DIVIDE(
     CALCULATE(
     SUM('Auto Production'[Production]), 
     FILTER('Auto Production','Auto Production'[Year]=MAX('Auto Production'[Year])
     )
     ), 
     CALCULATE(
     SUM('Auto Production'[Production]),
     FILTER('Auto Production','Auto Production'[Year]=MIN('Auto Production'[Year])))
    ,0) 
    - 1

    I color coded the DAX expression between the two equations to show which parts correlated.  Note we are using the DIVIDE function for division.  This is important because if we run into a case where we have a denominator = 0 then an error is returned.  Using DIVIDE allows us to return a zero instead of an error.

    Next add our newly created measure as a Card.

    Add Card
    Add Card

    Change the % Change measure format from General to Percentage, do this on the Modeling ribbon under Formatting.

    Change Measure Formatting
    Change Measure Formatting

    Next add a slicer for Year. 

    Slicer for Year
    Slicer for Year

    Now you can select different year and the % change will automatically change based on our selection.  The % change will always select the smallest year’s production and the largest year’s production to calculate the % Change.   By Selecting the Year 2013 and 2007, the percent change is 19.15%.  The smallest year is 2007 and the largest is 2013.

    Selecting Two Years
    Selecting Two Years

    If we select a year between 2013 and 2007 the measure will not change.

    Multiple Years Selected
    Multiple Years Selected

    The measure will only change when the starting and ending years are changed.  By selecting the year 2014, the measure finally changes.

    Selecting Additional Year
    Selecting Additional Year

    Pretty cool wouldn’t you say?  Thanks for taking the time to walk through another tutorial with me.

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

  • Measures – Dynamic CAGR Calculation in DAX

    Measures – Dynamic CAGR Calculation in DAX

    This tutorial walks through calculating a dynamic Compound Annual Growth Rate (CAGR).  By dynamic we mean as you select different items on a bar chart for example the CAGR calculation will update to reveal the CAGR calculation only for the selected data.  See the example below:

    Lets start off by getting some data.  For this tutorial we will gather data from World Bank found here.  To make this process less about acquiring data and more about calculating the CAGR. Below is the Query Editor code you can copy and paste directly into the Advance Editor.

    let
     Source = Excel.Workbook(Web.Contents("https://powerbitips03.blob.core.windows.net/blobpowerbitips03/wp-content/uploads/2017/11/Worldbank-DataSet.xlsx"), null, true),
     EconomicData_Table = Source{[Item="EconomicData",Kind="Table"]}[Data],
     #"Changed Type" = Table.TransformColumnTypes(EconomicData_Table,{{"Country Name", type text}, {"Country Code", type text}, {"Indicator Name", type text}, {"Indicator Code", type text}, {"1960", type number}, {"1961", type number}, {"1962", type number}, {"1963", type number}, {"1964", type number}, {"1965", type number}, {"1966", type number}, {"1967", type number}, {"1968", type number}, {"1969", type number}, {"1970", type number}, {"1971", type number}, {"1972", type number}, {"1973", type number}, {"1974", type number}, {"1975", type number}, {"1976", type number}, {"1977", type number}, {"1978", type number}, {"1979", type number}, {"1980", type number}, {"1981", type number}, {"1982", type number}, {"1983", type number}, {"1984", type number}, {"1985", type number}, {"1986", type number}, {"1987", type number}, {"1988", type number}, {"1989", type number}, {"1990", type number}, {"1991", type number}, {"1992", type number}, {"1993", type number}, {"1994", type number}, {"1995", type number}, {"1996", type number}, {"1997", type number}, {"1998", type number}, {"1999", type number}, {"2000", type number}, {"2001", type number}, {"2002", type number}, {"2003", type number}, {"2004", type number}, {"2005", type number}, {"2006", type number}, {"2007", type number}, {"2008", type number}, {"2009", type number}, {"2010", type number}, {"2011", type number}, {"2012", type number}, {"2013", type number}, {"2014", type number}, {"2015", type number}, {"2016", type number}, {"2017", type any}}),
     #"Removed Other Columns" = Table.SelectColumns(#"Changed Type",{"Country Name", "2011", "2012", "2013", "2014", "2015", "2016"}),
     #"Filtered Rows" = Table.SelectRows(#"Removed Other Columns", each [2011] <> null and [2012] <> null and [2013] <> null and [2014] <> null and [2015] <> null and [2016] <> null),
     #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Filtered Rows", {"Country Name"}, "Attribute", "Value"),
     #"Renamed Columns" = Table.RenameColumns(#"Unpivoted Other Columns",{{"Country Name", "Country"}, {"Attribute", "Year"}, {"Value", "GDP"}})
    in
     #"Renamed Columns"

    Note: The tutorial on how to copy and paste the code into the Query Editor is located here.

    Paste the code above into the advance editor.  Click Done to load the query into the the Query Editor.  Rename the Query to World GDP and then on the home ribbon click Close & Apply.

    World GDP Query
    World GDP Query

    Loading the query loads the following columns into the fields bar on the right hand side of the screen.

    Fields Load from World GDP
    Fields Load from World GDP

    Next we will build a number of measure that will calculate the required variables to be used in our CAGR calculation.  For reference the CAGR calculation is as follows: (found from investopia.com)

    CAGR Calculation Image
    CAGR Calculation

    For each variable on the right of the equation we will create one measure ; one for Ending Value, Beginning Value and # of Years.  On the Home ribbon click the button labeled New Measure.  Enter the following equation for the beginning value:

    Beginning Value = CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MIN('World GDP'[Year])))

    This equation totals all the items in the table called World GDP in the column labeled GDP.  This calculation will change based on the selections in the page view.

    Add two more measures for Ending Value and # of years

    Ending Value = CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MAX('World GDP'[Year])))
    # of Years = (MAX('World GDP'[Year])-MIN('World GDP'[Year]))

    Your fields list should now look like the following:

    Fields List with Measures
    Fields List with Measures

    Next add a Card visual for each new measure we added.  A measure is illustrated by the little calculator image next to the measure.  I have highlighted the Ending Value measure as a card for an example.

    Ending Value Measure as Card Visual
    Ending Value Measure as Card Visual

    Combining all the previous measures we will now calculate the CAGR value.  Add one final measure and add the following equation to calculate CAGR:

    CAGR = ([Ending Value]/[Beginning Value])^(1/[# of Years])-1

    This calculation uses the prior three measures we created.  Add the CAGR as a card visual to the page.

    Card Visual for CAGR
    Card Visual for CAGR

    Notice how the value of this measure is listed as a decimal, which isn’t very useful.  To change this to a percentage click on the measure CAGR item in the Fields list. Then on the Modeling ribbon change the format from General to Percentage.

    Format Change to Percentage
    Format Change to Percentage

    This changes the card visual to now be in a percentage format.

    Percentage Format
    Percentage Format

    Now you can add some fun visuals to the page and depending on what is selected the CAGR will change depending on the selected values.

    ProTip: To calculate the CAGR you can alternatively compute the entire calculation into one large measure like so:

    CAGR = ( [Ending Value] / [Beginning Value] )^(1/ [# of Years] )-1
    
    is the same as below:
    
    CAGR = (  CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MAX('World GDP'[Year])))  /  CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MIN('World GDP'[Year]))) ) ^ (1/  (MAX('World GDP'[Year])-MIN('World GDP'[Year]))  )-1

    A final recommendation is to wrap the CAGR calculation in an IFERROR function to make sure if one year is selected the measure doesn’t fail.  This returns a 0 if there is a calculation error of the equation. Documentation on IFERROR is found here.

    CAGR = IFERROR( ([Ending Value]/[Beginning Value])^(1/[# of Years])-1 , 0)

    To finish out the tutorial you can add the following visuals:

    Stacked Bar Chart Visual
    Stacked Bar Chart Visual – GDP by Year
    GDP by Country
    Stacked Bar Chart Visual – GDP by Country

    Note: you can sort the items in the stacked bar chart by selecting the ellipsis (the three dots in the upper right hand corner) and then selecting Sort By and clicking GDP.

    Country Sorted by GDP
    Country Sorted by GDP

    Finally select different items in the GDP by Year chart or the GDP by Country chart.  To select more than one item in the bar charts you have hold shift and left mouse click the multiple items.  Notice how all the measures change.

    Years 2013 & 2014 CAGR
    Years 2013 & 2014 CAGR

    Thanks for following along.

    This tutorial used the following materials:

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

  • Measures – Calculating a Sum

    Measures – Calculating a Sum

    Often there are times when you will want to display a totals.  Using measures to calculate a total are extremely easy to use.  The power of using a measure is when you are slicing and selecting different data points on a page.  As you select different data points the sum will change to reflect the selected data.  See sample of what we will be building today below.

    Materials for this Tutorial are:

    • Power BI Desktop (I’m using the April 2016 version, 2.34.4372.322) download the latest version from Microsoft Here.
    • CSV file with data, download SampleData in CSV format.

    To load the CSV file into Power BI Desktop you can follow along in this tutorial, Import CSV File into PowerBI Desktop.

    Once you’ve loaded the CSV file into Power BI Desktop your fields items should resemble the following:

    Fields List
    Fields List

    Add the Table visual from the visualizations bar into the Page area.  Drag the following items into the newly created table visualization, Category, Sales, and ID.  Your table should look like the following:

    Table of Data
    Table of Data

    Click the Triangle next to the ID column under the Values section in the Visualization bar.  A menu will appear, select the top item labeled Don’t Summarize.

    Do not Summarize Data for ID
    Do not Summarize Data for ID

    This reveal all the unique items in our table of data.  Now, we will create our measures for calculating totals.  On the Home ribbon click the New Measure button.  Enter in the following DAX expression.

    Total Sales = SUM(SampleData[Sales])

    Note: In the equation above everything before the equals sign is the name of the measure.  All items after the equation sign is the DAX expression.  In this case we are taking a SUM of all the items in the Table SampleData from the column labeled Sales.

    This will total all the items in the sales column.  Click on the Card visual and add the Total Sales measure to the card.  Your new card should look like the following.

    Total Sales Measure
    Total Sales Measure

    Next we will add a bar chart to show how the data changes when the user selects various items on the page to filter down to different results.  Add the Stacked Bar Chart to the page.  In the Axis & Legend selectors add the Category column, and add the Sales column to the Value selector.  This will yield the following bar chart.

    Bar Chart
    Bar Chart

    Now we can click on items in the bar chart to see how the table of data and the Total Sales changes for each selection.  Clicking on the bar labeled Apples provides a total sales of 283, and clicking on the Oranges shows a total of 226.

    Apples Bar Selected
    Apples Bar Selected

    Our measure is complete.  Now we can select different visualizations and each time we do PowerBI is filtering the table of available data down to a smaller subset.

    Pro Tip: When building different visuals and measures often it is helpful to have a table showing what data is being filtered when you interact with the different visuals.  Sometimes the filters that you are applying by clicking on a visual interact in non-expected ways.  The table helps you see these changes.

    We have now completed a measure that is calculating a total of all the numeric values in one column.

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

  • Measures – Calculating % Change

    Measures – Calculating % Change

    In our last post we built our first measure to make calculated buckets for our data, found here.  For this tutorial we will explore the power making measures using Data Analysis Expressions (DAX).

    When starting out in Power BI one area where I really struggled was how to created % change calculations.  This seems like a simple ask and it is if you know DAX.

    Alright lets go find some data.  We are going to go grab data from Wikipedia again.  I know, the data isn’t to reliable but it is fun to play with something that resembles real data.  Below is the source of data:

    https://en.wikipedia.org/wiki/Automotive_industry

    To acquire the data from Wikipedia refer to this tutorial on the process.  Use the Get Data button, click on Other on the left, select the first item, Web. Enter the webpage provided above in the URL box.  Click OK to load the data from the webpage.  For our analysis we will be completing a year over year percent change.  Thus, select the table labeled By Year[edit].  Data should look like the following:

    Global Auto Production Wikipedia
    Global Auto Production Wikipedia

    This is the total number of automotive vehicles made each year globally from 1997 to 2014.  Click Edit to edit the data before it loads into the data model.  While in the Query Editor remove the two columns labeled % Change and Source.  Change the Name to be Global Production.  Your data will look like the following:

    Global Production Data
    Global Production Data

    Click Close & Apply on the Home ribbon to load the data into the Data Model.

    Add a quick visual to see the global production.  Click the Area Chart icon, and add the following fields to the visual, Axis = Year, Values = Production.  Your visual should look something like this:

    Area Chart of Global Production
    Area Chart of Global Production

    Next we will add a table to see all the individual values for each year.  Click the Table visual to add a blank table to the page.  Add Both Year and Production to the Values field of the visual.  Notice how we have a total for both the year and production volumes.  Click the triangle next to Year and change the drop down to Don’t summarize. 

    Change to Don't Summarize
    Change to Don’t Summarize

    This will remove the totaled amount in the year column and will now show each year with the total of Global Production for each year.  Your table visual should now look like the following:

    Table of Global Production
    Table of Global Production

    Now that we have the set up lets calculate some measures with DAX.  Click on the button called New Measure on the Home ribbon.  The formula bar will appear.  We will first calculate the total production for 2014.  We will build on this equation to create the percent change.  Use the following equation to calculate the sum of all the items in the production column that have a year value of 2014.

    Total 2014 = CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2014))

    Note: I know there is only one data point in our data but go alone with me according to the principle.  In larger data sets you’ll most likely have multiple numbers for each year, thus you’ll have to make a total for a period time, a year, the month, the week, etc..

    This yields a measure that is calculating only the total global production in 2014.  Add a Card visual and add our new measure “Total 2014” to the Fields.  This shows the visual as follows, we have 90 million vehicles produced in 2014.

    2014 Production
    2014 Production

    Repeat the process above instead use 2013 in the Measure as follows:

    Total 2013 = CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2013))

    This creates another measure for all the production in 2013.  Below is the Card for the 2013 Production total.

    2013 Production
    2013 Production

    And for my final trick of the evening I’ll calculate the percent change between 2014 and 2013.  To to this we will copy the portions of the two previously created measure to create the percent change calculation which follows the formula [(New Value) / (Old Value)]- 1.

    % Change = CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2014)) / CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2013)) - 1

    This makes for a long equation but now we have calculated % change between 2013 and 2014.

    Percent Change
    Percent Change

    Wait you say.  That seems really small, 0.03 % change is next to nothing.  Well, I applaud you for catching that.  This number is formatted as a decimal number and not a percentage, even though we labeled it as % change.  Click the measure labeled % Change and then Click on the Modeling ribbon.  Change the formatting from General to Percentage with one decimal.  Notice we now have a percentage.

    Change Format to Percentage
    Change Format to Percentage

    Thanks for working along with me.  Stay tuned for more on percent change.  Next we will work on calculating the percent change dynamically instead of hard coding the year values into the measures.

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

    Please share if you liked this tutorial.