Tag: Tutorials

  • Using Parameters to Enable Sharing

    Using Parameters to Enable Sharing

    This week I had a number of team members tell me how difficult it was to share a PBIX file and the corresponding data between team members.  The department hasn’t committed 100% to the idea of using PowerBI.com, and thus wanted to share the actual report.  I pointed my team mates to my earlier tutorial about using variables for file locations.  After reading the tutorial the team came back with a bunch of griping about how they didn’t want to go into the query editor, people name variables different things, and thus it’s hard to understand what another team member was doing, blah, blah, blah…

    So, in order to make peace I took another look at trying to make the sharing of a PBIX file easier.  This time I decided to use the Parameters feature within PowerBI.  This feature within the Query Editor was released all the way back in April of 2016.  I read about it, thought it was interesting but couldn’t find a really good use case.  In my current predicament, the parameters feature is the perfect solution.

    By using a parameter to store a folder and or file location you enhance the user experience by making it easier for a user to change the Query.

    To modify a parameter after it has already been built click on the bottom half  of the Edit Queries button, found on the Home ribbon.  A menu will pop up and you can select Edit Parameters.

    Edit Queries
    Edit Queries

    The Enter Parameters screen will pop up.  This is where you would change the parameters for a query.  In our example this is where we will enter a new folder location for our data.

    Enter Parameters Screen
    Enter Parameters Screen

    Let’s begin the tutorial.  To start we will need to work with some data.  In my earlier tutorial, I used the Olympic Medals Count.  We will reuse this dataset.  Start by downloading the zipped folder Olympic Metal Count files from the following location.  Once you have downloaded the sample data, extract the folder and subsequent files from the zipped file.  In windows 10, which I am using, you can right click on the downloaded file and select Extract All..

    Extract All from Zipped Folder
    Extract All from Zipped Folder

    A pop-up window will appear to complete the extraction process. By leaving the default settings the folder will be extracted into the same location as the downloaded file. Click Extract to complete the extraction.

    Complete Extraction
    Complete Extraction

    We now have a folder with all our data.

    Extracted Folder
    Extracted Folder

    With the data prepared we can now make the parameters within PowerBI.  Open PowerBI and click the top half of the Edit Queries button.  The Query Editor will open.  Click the Mange Parameters found on the Home ribbon.  The Parameters screen will open.  Click the blue New button at the top left.  Enter the name Folder, and include a brief description of this parameter.  Since the folder parameter is essential to the query we must leave the Required box checked.  Change the Type to Text, and leave the Suggested Values to Any value.  Finally enter the Folder Location where our Medal-Count file is located into the Current Value.  Click OK to complete the parameter.

    Make Parameter
    Make Parameter

    Next, we will create the actual query to load the folder containing our Metal Counts.  Click on the New Source button.  This will open the Get Data window.  Select the Folder option located in the list on the right.  Click Connect to complete the Get Data.

    Connect to Folder
    Connect to Folder

    The Get Data window will close, then a new window asking for the folder location will open.  This is where the parameter implementation is slick.  Click the ABC button to the far right of the Folder Path bar.  Change the selection to Parameter and select our newly created parameter labeled Folder.  Click OK to load the Folder.

    Change to Parameter
    Change to Parameter

     

    Select Folder
    Select Folder

    Next the folder prompt opens allowing us to accept or edit the query.  Click Combine & Edit to proceed.  The Combine Files window will open.  Here we can interrogate each file to inspect what is in each file.  Clicking the drop-down menu next to Example File: allows us to see the list of all files.  Select the 2004 Medals.xlsx file.

    Select Drop Down
    Select Drop Down

     

    Click the Sheet1 item on the left side of the window.  This exposes the data that is contained within this 2004 particular file.  Click OK to proceed.

    Select Sheet1
    Select Sheet1

    Note: For users that have been working with PowerBI for a while, this Combine Files screen flow is a newer feature.  I feel that this greatly simplifies the process and makes it easier to detect issues when loading data. 

    PowerBI now loads the files into the Query Editor.  The Query that we want to use is labeled Query2, change the Query2 name to Metal Count.

    Metal Count
    Metal Count

    What you’ll also notice is there is a lot more queries on the left side of the screen under Queries.  These queries were auto generated when we navigated through the menu screens. Click Close & Apply to complete the data load.

    Build the following Stacked Column Chart:

    Stacked Column Chart
    Stacked Column Chart

    Click the Ellipsis on the upper right hand corner of the chart and select Sort By Total to sort all the items in the bar chart according to how many metals each country won.

    Sort by Total
    Sort by Total

    Great we have made a parameter, loaded multiple excel files, and then made a visual of our data.  Let’s test it out. Save your work and close the PowerBI desktop.  (don’t forget to save your PBIX)

    Next we rename the folder where all the excel files are contained.  Change the name to Olympic Medals.

    Rename File Folder
    Rename File Folder

    Reopen your PBIX file, on the Home ribbon click the Refresh button.  Ooops, since we renamed the folder we now have an error.

    Error Screen
    Error Screen

    To fix this click the bottom half of the Edit Queries button on the home ribbon, and select Edit Parameters.  Then modify the Folder field to include the new name of the other folder Olympic Medals. Click OK to proceed.

    Edit Folder Location
    Edit Folder Location

    A message bar will appear under the Home ribbon.  Click Apply Changes to complete the data load.  PowerBI will reload all your data using the context of the new folder.

    Now this is an elegant solution for sharing PBIX files and their corresponding data files with coworkers.  This is just a simple example of how you would use parameters.  There are a multitude of other really good use cases for using parameters within your queries.  Thanks for reading along, be sure to share if you like this tutorial.

  • Import Color Theme & Color Theme Generator

    Import Color Theme & Color Theme Generator

    March is an exciting month, and with this release of Power BI we have been given some long asked for features. One such feature is the ability to import a color theme. The color theme defines the starting colors for your visuals. Before the ability to import a theme one would have to first define each color that they want to use in a Power BI report by changing each visual to have the correct color scheme. Color themes are useful when trying to make a dashboard and you want to use colors that resemble a company’s product or logo. Alright, let’s get started and make and add our own color theme to a report.

    Begin by opening up Power BI Desktop. Make sure you have the latest version of Power BI Desktop, you can download the latest version here. The import color theme feature is available in the March 2017 release.

    On the Home ribbon click the Enter Data button.  Enter the following table of data and name the table Data.

      Product    Value
    Item120
    Item225
    Item315
    Item440

    The Create Table should look similar to the following.  Click the Load button to proceed.

    Load Data Table
    Load Data Table

    Power BI will load the data to memory and the Fields pane will reveal our newly created columns. Add the Stacked Column Chart on the report page and appropriate fields shown in the image below.  You will notice that the default colors are automatically overlaid onto our visual when we add the Product to the Legend visual field.

    Add Stacked Column Chart
    Add Stacked Column Chart

    Next, let’s take a peek at the standard colors that are offered by default from Power BI.  Click on the Paint Roller found in the Visualizationpane.  Then expand the data field labeled Data colors.  Under Item1 click the little triangle.  This will expose the current color scheme that is loaded.

    Default Color Scheme
    Default Color Scheme

    Now we will load the new color theme.  But before we can load the color theme we have to generate the color theme first.  The color theme has some requirements.  First the color theme must be written as a JSON file and must adhere to the JSON format.  For developers this will be a very simple google search to accomplish this.  However, I know there are some out there that do not enjoy doing development work.  So, in a PowerBI.Tips first, I have developed a custom tool to make the color theme generation super simple.

    Introducing the PowerBI.Tips Color Theme Generator (CTG) to help Power BI users create quick and easy JSON code files to input into Power BI for the color themes. Not everyone has a coding background, and though there will be tutorials and examples of how to set up the JSON, if you aren’t familiar with the language a small typo could have you spending precious time troubleshooting the issue.

    update 3/15/17: The Advanced Theme Generator has been released.  Find the tool here.

    Click the following link to open up the PowerBI.Tips Color Theme Generator in a different Browser window.  Once the browser loads the Color Theme Generator follow the instructions listed at the top of the page to select your colors.  The only required fields are the Name, and at least one color.  For this tutorial I selected a number of nice pastel colors.  Click the Download Color Theme button to download the JSON file that we will use in Power BI.

    Note: The Generator was tested on Google Chrome.  Also, clicking the Download button will download the JSON file to your browser’s default location.  You will need to know this file location to load the file into Power BI Desktop. 

    PowerBI.Tips Color Theme Generator
    PowerBI.Tips Color Theme Generator

    Head back over to Power BI Desktop.  On the Home ribbon click the button labeled Switch Theme.  Then click Import Theme.

    Import Theme Button
    Import Theme Button

    Note: If you want to remove your custom theme you will click on the Switch Theme, then click on the Default Theme.  The normal power BI colors will be restored.

    Navigate to where your browser downloaded the file.  Select the file labeled PowerBI-Tips Color Theme.  Click Open to load the theme.

    Load Color Theme
    Load Color Theme

    PowerBI will prompt a message letting you know everything loaded correctly. Click Close to see the new theme applied to our visual.

    Theme Load Successful
    Theme Load Successful

    We can now see our custom theme by clicking on the Paint Roller found in the Visualizations pane.  Then expand the data field labeled Data colors.  Under Item1 click the little triangle.

    Tada, now we have a custom color scheme that we create and loaded.  Also, now that we the JSON file you can modify the file and keep it for future projects.

    Loaded Custom Color Theme
    Loaded Custom Color Theme

    Thanks for following along.  If you liked this tutorial please be sure to share.  Also if you want to know more about me you can visit my About page and follow me on twitter or Linkedin for updates.

  • Get Your OData Here

    Get Your OData Here

    For those of you who are following my tutorials, you are most likely to understand that each tutorial comes with it’s own data source.  This has been intentional so we can both walk through the example and learn by doing.  Whenever, I am learning new things I find it’s helpful to do two things.   First, make examples and demos of what I am trying to learn.  Simply reading about a tool such as PowerBI, while engaging, it isn’t how I learn.  I learn by getting my hands dirty, opening up PowerBI and creating something.  You have to get utterly frustrated and stumped before that light bulb pops on and things become clear.  Secondly, after I’ve taken the time to learn a new feature or method I find it extremely helpful to teach someone else what I’ve learned.  By doing so, I am able share in the enthusiasm of others who also are learning.  Teaching others also makes you remove all the cluttered ideas away from the essential lesson.

    This being said, I consume a lot of data.  Always finding data sources is difficult.  Often I find myself making up my own data sets which takes additional time.  At least, it used to take me forever to find data.  This past week I was digging around for more data sources and I stumbled upon this gem.  It is the data source has been used by many a bloggers for examples.  It is Adventure Works sample business database.  For this tutorial we will walk through how to load the Adventure Works dataset directly in to PowerBI.

    Lets begin by opening Power BI desktop.  Once Power BI desktop is open on the Home ribbon click the Get Data button.  The Get Data window will open and under the Other section we find an OData Feed.  Select the OData Feed and then click Connect to proceed.

    Select OData Feed
    Select OData Feed

    The OData Feed window will open.  Enter in the following HTML address into the URL field.

    http://services.odata.org/AdventureWorksV3/AdventureWorks.svc

    Note: In this example we are only using the basic OData Feed connection.  Power BI does allow users to build more complex OData feeds which may require multiple parameters.  This functionality is included by toggling the OData Feed screen from Basic to Advanced. This would be ideal if you had an OData Feed such as http://myOdataFeed.com/{custom parameter}/OData.  

     Click OK to proceed

    Enter OData Feed
    Enter OData Feed

    Power Bi will now go to the web address and read the OData Feed.  What is returned is a list of tables.  The Navigator window shows us previews of each table.  Select the CompanySales and TerritorySalesDrillDown by checking the boxes next to each table.  Click Load to proceed.

    Select Tables
    Select Tables

    Ta Da!! that was easy.  We were able to quickly load the two tables from the Adventure Works database.  We can confirm this by looking at all the loaded fields contained in the Fields pane.

    Loaded Fields
    Loaded Fields

    Add a couple of visuals with the following fields to pretty up our page.

    Add Clustered Column Chart
    Add Clustered Column Chart

    Add Stacked Bar Chart
    Add Stacked Bar Chart

    Pro Tip: notice how the two charts we added have the same color scheme but are different dimensions.  The Clustered Column Chart has Years for the Colors, but the Stacked Bar Chart is using product categories.  Change the colors on the Stacked Bar Chart by clicking on the Paint Roller on the Visualizations pane.  Select the section called Data Colors and modify the colors for each product category.

    Change Stacked Bar Chart Colors
    Change Stacked Bar Chart Colors

    Note: In order to sort from the largest sales amount to the smallest.  Click the Ellipsis (small three dots) on the corner of the visual and select Sort by Sales.  This will make the visual sort in order of sales from the highest amount to the smallest amount. 

    Similarly you can change the colors for the Clustered Column Chart to make the visual more appealing.

    Change Clustered Column Chart Colors
    Change Clustered Column Chart Colors

    Add Waterfall Chart
    Add Waterfall Chart

    Again using the Ellipsis of the visual select Sort by Total to sort the number of sales by each employee from the largest sales amount, Linda to the smallest sales amount Lynn.  Also, note that this chart is being built off the second table that we loaded from the OData Feed labeled TerritorySalesDrilldown.

    Now, I believe we can say we are officially done.  We have loaded data from our OData Feed and created three visuals upon that data. Thanks again for following along.

    If you liked this tutorial please be sure to share.  Also if you want to know more about me you can visit my About page and follow me on twitter or Linkedin for updates.

     

  • Improved Matrix Headers

    Improved Matrix Headers

    Power BI has been an continually evolving tool over the last year.  The Matrix visual is powerful and mimics much of the functionality of a Pivot Table within Excel.  I will admit, the Matrix visual has some features that are left to be desired.  One such feature, the ability to word wrap row headers, has been resolved in the February 2017 update of PowerBI.  See the official release notes for details.  In my company we have traditionally been an excel driven business.  All you other heavy analytics people you know what I’m talking about.  Emails upon emails about an excel analysis, then power point presentations of those excel documents.  Inevitably a pivot table or table will end up on a power point slide.  Icky, if you ask me, especially when you have to “refresh” the data… I digress, Power BI fills a great gap in this area where the Analytics leaders within your company can make reports that easily refresh, and look dang sexy.

    The Matrix is one of those visuals that I would say is a comfortable way for non-analytical people to review data.  The Pivot Table aka Matrix in Power BI, is how people have been used to looking at data for years.  This has been quite a sticking point for many business leaders when reviewing Power BI dashboards.  I’ll present some data using a map or bar chart and I’ll usually get the, “Where’s the table of data?”  This will prompt an additional tab inside the Power BI document with a large data table.  Presenting headers in that large table or matrix has always been a challenge because the headers don’t word wrap.  Seeing Microsoft listening to people’s feedback and implementing header word wrap and other features is refreshing.

    For this tutorial we will be working with a dataset that I found from the FBI titled Crime in the United States.  I chose this data set based on the flurry of media talking about the current President’s comments about crime.  Before we move on, let me assure you this will not have any politics in this tutorial.  Therefore, it will be safe to read on.

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

    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/2017/02/US-Crime-Data.xlsx"), null, true),
        #"US Crime Data_Sheet" = Source{[Item="US Crime Data",Kind="Sheet"]}[Data],
        #"Promoted Headers" = Table.PromoteHeaders(#"US Crime Data_Sheet", [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"State", type text}, {"Area", type text}, {"Violent Crime", Int64.Type}, {"Murder and Non-negligent Manslaughter", Int64.Type}, {"Robbery", Int64.Type}, {"Aggravated Assault", Int64.Type}, {"Property Crime", Int64.Type}, {"Burglary", Int64.Type}, {"Larceny Theft", Int64.Type}, {"Motor Vehicle Theft", Int64.Type}}),
        #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"State", "Area"}, "Attribute", "Value")
    in
       #"Unpivoted Other Columns"

    Before you exit the query editor Rename the query to US Crime. It should look similar to the following:

    US Crimes Data Load
    US Crimes Data Load

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

    Lets add a little color to the Page in the form of a map.  Inside the Visualizations pane click on the Shape Map visual.  Add the appropriate fields as shown in the image below.

    Shape Map Visual
    Shape Map Visual

    We added this map as to make our page look pretty as well as, we can now click on each state and use this as a filtering mechanism.

    Next, add the Matrix visualization which is found on the Visualizations pane.  Add the fields shown in the image below.

    Add Matrix Visualization

    To illustrate the wrapped row headers as described in the Power BI blog simply hover your mouse over the header until a double arrow appears.  Then left click on the mouse to select the edge of the Area column.

    Cursor Hovering Over Area Column
    Cursor Hovering Over Area Column

    Drag the edge of the Area column left until it covers some of the text of the row labels, see below for example.

    Shortened Area Column
    Shortened Area Column

    Next, in the Visualizations pane click on the Paint Roller and expand the section labeled Row headers.  In the Row headers section toggle the Word wrap switch to On.

    Word Wrap On
    Word Wrap On

    After turning the Word wrap on you’ll notice that row headers did not word wrap.  This is because the row headers have a caveat.  The word wrap in rows will only work if row grouping is long enough to accommodate the word wrap.  To illustrate this, add the State field underneath the Area field in the Rows section in the Visualizations pane.

    Add State to Rows
    Add State to Rows

    We can now see by adding the States after the Area field that the Area Cities Outside Metropolitan Areas now has enough room to word wrap.  An important observation with the row headers word wrap is that the word wrap will be affected by other filtering selections on the visual page.  For example if I only select the state of Texas the row header for Area does not have enough room and therefore it is shortened and the “…” appears.

    Texas Selected
    Texas Selected

    When I was first exploring the Matrix row Headers Wrap I was quite confused on how I was able to actually make the headers wrap.  After playing around with the feature a while I was able to figure out the functionality.  Thanks for following along, see that wasn’t so political.  Now you can take this wonderful knowledge back to your workplace and make promises you can keep (OK, there it was, insert political jab).

    If you liked this tutorial please be sure to share.  Also if you want to know more about me you can visit my About page and follow me on twitter or Linkedin for updates.

  • Measures – Year Over Year Percent Change

    Measures – Year Over Year Percent Change

    This tutorial is a variation on the month to month percent change tutorial.  This specific exploration in year over year performance was born out of reviewing my google analytics information.  The specific analysis question I am trying to answer is, how did this current month of website visitors compare to the same month last year.  For example I want to compare the number of visitors for November 2016 to November 2015.  Did I have more users this year in this month or last year?  What was my percent changed between the two months?

    Here is a sample of the analysis:

    let’s begin with loading our data and data transformations.  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, click Done to complete the data load.

    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 = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("VdDBDcQwCETRXnyOFMAYcC1W+m9jV8BhfH1ygJ9zBr/8CvEaz+DYNL7nDAFjnWkTTNsUbIqnLfyWa56BOXOagy2xtMB5Vjs2mPFOYwIkikIsWd6IKb7qxH5o+bBNwIwIk622OCanTd2YXPNUMNnqFwomp0XvDTAPw+Q2uZL7QL+SC1Wv5Dpx/lO+Hw==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [#"Start of Month" = _t, Sales = _t]),
     #"Changed Type" = Table.TransformColumnTypes(Source,{{"Start of Month", type date}, {"Sales", Int64.Type}}),
     #"Inserted Month" = Table.AddColumn(#"Changed Type", "Month", each Date.Month([Start of Month]), type number),
     #"Inserted Year" = Table.AddColumn(#"Inserted Month", "Year", each Date.Year([Start of Month]), type number)
    in
     #"Inserted Year"

    While still in the Query Editor rename the query to Data.  Then click Close & Apply to complete the data load into the data model.

    Load Monthly Data
    Load Monthly Data

    Next, make four measures.  On the Home ribbon click the New Measure button.  Enter the following to establish a reference date to the subsequent equations:

    Date Reference = DATE(2016,12,31)

    Enter in the following equation to calculate the last year monthly sales amount.

    LastYear = 
      VAR 
        CurrentDate = [Date Reference]
      RETURN
        CALCULATE( 
         SUM(Data[Sales]), 
         Data[Year] = YEAR(CurrentDate)-1
        )

    Note: Using the NOW() function calls the current time when the query was last run.  Thus, if you refresh your data next month the NOW() function wrapped in a YEAR() will return the current year from the date-time observed by PowerBI.

    Following the same process enter the following additional measures.  The ThisYear measure calculates the sales for the current month.

    ThisYear = 
      VAR 
       CurrentDate = [Date Reference] 
      RETURN
       CALCULATE(SUM(Data[Sales]),Data[Year] = YEAR(CurrentDate))

    Finally, add the calculation for the Year to Year comparison.

    YoY Percent Change = DIVIDE([ThisYear], [LastYear], 0)-1

    Since the YoY Percent Change is a real percentage we need to change the formatting to a percent.  Click on the YoY Percent Change measure then on the Modeling ribbon click the symbol in the formatting section of the ribbon.

    Change Measure Format
    Change Measure Format

    Next, add a Stacked Column Chart with the following columns selected.

    Add Stacked Column Chart
    Add Stacked Column Chart

    OK, we have a chart, but it is kinda awkward looking right now.  The x-axis is the month number but we don’t have a month 0.  That simply does not make sense.  Let’s change some of the chart properties.  While having the Stacked Column Chart selected click on the Paint Roller in the Visualizations pane.  First, click on the X-Axis and change the Type to Categorical.

    Change X-Axis
    Change X-Axis

    Then click on the Data Colors and turn on Diverging.  Change the Minimum color to Red and the Maximum color to Green.  Set the Center to a value of 0.

    Change Colors
    Change Colors

    Click on the Title change it something meaningful, Center the text and increase the font size.

    Change Title
    Change Title

    Our bar chart looks much better.  However, the month numbers do not look quite right.  Visually the month indicators would be cleaner if we didn’t have any decimals.  Click on the Month field and then on the Modeling ribbon change the Data Type to Whole Number.  There will be a warning letting you know that you are changing the Data Type of the Whole number.  Click OK to proceed with the change.

    Change Month to Whole Number
    Change Month to Whole Number

    Another successful percent change tutorial completed.  I hope you enjoyed this year over year month comparison example.  Make sure you share if you like what you see.

  • Grouping and Improved Date Slicer

    Grouping and Improved Date Slicer

    In the October update of PowerBI Desktop we were given a number of really useful features, ranging from a new Date Slicer, Grid lines, Grouping, Binning, Top N Filters, and R-powered custom visuals.  For the full release on the October 2016 software release you can read more here.

    For those of you who have followed my site you already know that I absolutely love the ability to create R-visuals within PowerBI.  If you want to learn more you can read the R script tutorials here.

    As I’ve been exploring this October release of Power BI Desktop two features have really stood out.  First, the ability to use the Date Slicer and second the new feature of Grouping for Bar Charts.  In my daily work flow I have struggled in the past with solutions which are now solved.

    Welcome to my love & hate relationship with time bound data sets.  Inevitability at some point you will encounter a need to manipulate data over time.  Common business questions will come in the form of:  What was my percent change compared from this month compared to last month?  What is my sales performance for this year? Are we up or down compared to the same period last year?  While these questions are simple I have found that calculating measures and subsequently building visuals can get very complex in a hurry.  Enter the Date Slicer.  Let me be clear, the Date Slicer will not solve all your problems, it does present a very useful interface that will let report users quickly navigate through their time delineated data.

    What is the Date Slicer?  I’m glad you asked. Behold….

    Date Slicer
    Date Slicer

    Here are a couple of key items to point out.  On the left side of the visual you are given the ability to select the starting date, and ending date.

    Start and End Dates
    Start and End Dates

    The bottom of the Date Slicer has an adjustable time bar that allows quick time adjustments.

    Changed Timeline
    Changed Timeline

    On the right side of the visual you can toggle between different date selection modes, Between, Before, After, and List.

    Time Parameter Selector
    Time Parameter Selector

    Ok, enough about the Date Slicer, how about the Groupings feature.  Lets say you start off with a bar chart that looks similar to the following:

    Sample Bar Chart
    Sample Bar Chart

    Well, maybe you’re only interested in Items 9, 10, and 5.  Grouping now allows the selection of multiple bars and by right clicking you can Group, Include, or Exclude.

    Right Click on Selected Data Bars
    Right Click on Selected Data Bars

    Clicking group creates a new column in the Fields area that groups the items together and adds them to the chart legend.

    Grouped Items in Bar Chart
    Grouped Items in Bar Chart

    Let me tell you this is helpful, especially when your bar chart looks like this:

    Ugly Bar Chart
    Ugly Bar Chart

    Be honest, you have published a report or two when there were just way to many bars.  The different between the largest bar and all the small bars barely tells you any information.  This is why grouping is helpful.  When you receive data and you need to focus your story to the important pieces then grouping is your friend.

    Enough babbling, let’s get to the tutorial.

    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, click Done to complete the data load.

    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/11/Sales-Data-Two-Years.xlsx"), null, true),
     Sales_Table = Source{[Item="Sales",Kind="Table"]}[Data],
     #"Changed Type" = Table.TransformColumnTypes(Sales_Table,{{"Date", type date}, {"Product", type text}, {"Sales", Int64.Type}})
    in
     #"Changed Type"

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

    Load Sales Data
    Load Sales Data

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

    Close and Apply
    Close and Apply

    Great, we are ready to start adding visuals now.  Add a Slicer visual from the Visualizations window and populate the visual with the Date field.  By default, the slicer will auto recognize that the field being added is a date and will automatically show the Date Slicer.

    Add Date Slicer
    Add Date Slicer

    Next, add a bar chart visualization.  The Date field will be the Axis, and the Sales will be the Value.

    Add Bar Chart
    Add Bar Chart

    Again by default the Date filed will be entered as a Hierarchy field.  Click the Drill Down button until you see a monthly view of the date.  This should require two clicks, the first drills down to quarters, then second click drills down to month level.  After doing this your visual should look like the following:

    Drill Down to Month
    Drill Down to Month

    Add a second bar chart with following fields selected.

    Second Bar Chart
    Second Bar Chart

    Sort the Sales by Product bar chart in descending sale order by clicking the Ellipsis and when the drown down menu appears selecting Sort by Sales.

    Descending Sort by Sales
    Descending Sort by Sales

    Now that we have built a couple visuals and a Date Slicer, take some time to explore how the Date Slicer interacts with the bar charts.  In the example below I modified the starting date to 6/1/205 and the ending date to be 9/30/2015.

    Modify Date Slicer Properties
    Modify Date Slicer Properties

    To utilize the grouping feature we will group Items 1,2,3 and 4 together.  While holding the control button click Items 1,2,3 and 4 on the Sales by Product bar chart.

    Ctrl Click Items
    Ctrl Click Items

    Right click Item 3 an menu will appear, select Group.  Notice once you do this a new Product (Group) field appears in the field menu and the Product (Group) is automatically added to the legend of the bar chart visual.

    Grouping in Bar Chart
    Grouping in Bar Chart

    To edit the grouping you can click on the Field labeled Product (groups) and select Edit Groups.  Doing this reveals the grouping dialog box.

    Grouping Dialog Box
    Grouping Dialog Box

    You can rename the created group by double clicking the name Item 1 & Item 2 & Item 3 & Item 4.  

    Rename Grouping
    Rename Grouping

    Change the name of the grouping to be titled Special Items.  Click OK to close the Groups dialog box. Notice how the bar chart updates the legend values to renamed grouping.

    Rename Group
    Rename Group

    Well, that wraps up this tutorial.  I hope you enjoyed it.  Below is a live demo of what we built today.

    Make sure you share the content if you liked this tutorial.

  • 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.

  • Fixing Measure Madness

    Fixing Measure Madness

    Often times when you’re working with large data models you will have multiple tables with many relationships.  It could be complex maybe you’ve seen something like the following:

    Large Data Model
    Large Data Model – Photo Credit ( www.biinsight.com )

    Once all the tables have been loaded the manic measure building begins to support all the different visuals.  A couple of sums here, a number of calculates over there, and boom, a beautiful report.  You stand back and survey the work and realize you’ve built measures all over the place, in different tables, maybe even stuck a couple of measures in the wrong place.  Whoops.

    Tons of Measures
    Tons of Measures

    Maybe we should think about cleaning things up a bit, if only there was a way to group the measures.  How do I group my measures?  I’m glad you asked.  With a little trickery we can make a measure table.  Let’s begin.

    First we will load a little data.  For this tutorial we will simply copy and paste in some data.

    Note: For the full tutorial on manually entering in data visit this page.

    On the Home ribbon click the Enter Data button.  Copy in the table below into the Create Table window.  Rename the table Sales Data and click Load to exit.

    Salesman Item Unit Sales Revenue
    Salesman 3 Item 4 405 1357
    Salesman 1 Item 3 339 1649
    Salesman 1 Item 3 315 1332
    Salesman 3 Item 3 418 1531
    Salesman 1 Item 3 482 1633
    Salesman 2 Item 4 448 1676
    Salesman 1 Item 4 391 1432
    Salesman 2 Item 1 341 1539
    Salesman 3 Item 1 419 1482
    Salesman 2 Item 4 414 1610
    Salesman 1 Item 4 351 1670
    Salesman 3 Item 3 449 1795

    Manually Enter Data
    Manually Enter Data

    Upon loading our data table we now have the following fields.

    Fields of Data
    Fields of Data

    Now, let’s make a measure that calculates the revenue per unit.  On the Home ribbon click the New Measure button and enter the following DAX measure.

    Revenue Per Unit = SUM('Sales Data'[Revenue]) / SUM('Sales Data'[Unit Sales])

    Next, make a table with the following fields.

    Salesman Table
    Salesman Table

    Great! but, as we all know this is how the measure madness begins.  From here we refine and finesse the data to craft the data story, and end up with tons of additional tables and measures.

    Pro Tip: You can use the search window at the top of the Fields window to help you find buried measures or fields of data. 

    Using Search in Fields
    Using Search in Fields

    Let’s make the measure table.  Start by clicking Enter Data on the Home ribbon.  Rename the new table to My Calcs, and rename Column1 to Calcs.   You don’t have to re-name column1, but since I’m OCD about my data I like to rename the column to the same name as the table.  Then click Load to exit the screen.

    Measure Table Load
    Measure Table Load.

    We now have a new table labeled My Calcs with one column labeled Calcs.  Next highlight the measure we created Revenue Per Unit.  Then on the Modeling ribbon change the home table from Sales Data to My Calcs.  This will move the measure.

    Home Table for Measure
    Home Table for Measure

    Right click on the Calcs column in the My Calcs table and then select Hide.

    Hide Calcs Column
    Hide Calcs Column

    Next Save and then reopen the document (it’s a Microsoft thing I guess).  After the document has reopened the My Calcs table has changed it’s icon from a table to a Measure icon.

    Completed Measures Table
    Completed Measures Table

    For kicks and giggles add the following measure to the My Calcs table.

    Total Revenue = SUM('Sales Data'[Revenue])

    Ok, one more.

    Total Unit Sales = SUM('Sales Data'[Unit Sales])

    There you go.  A very straight forward approach to cleaning up all the random measures in your data model.  I have found that when others team members are working with your data model this helps other people understand which fields have been calculate and which ones were imported via a query.  This also helps you group logical calculations, further creating clarity within your data model.

    If you want to read up more on making measure tables check out this great site (also linked below).  In addition to walking you through creating a measure table it also explains how to make a measure table when using direct query mode.  As the article explains, while you are in direct query mode you are unable to manually enter data.  Nice job, Soheil Bakhshi, well done.

    How to Define A Measure Table in Power BI Desktop

    If you want to take your DAX skills to the next level, try jumping into this book by Rob Collie and Avichal Singh.  It’s an easy read but very insightful.

    If you liked this tutorial make sure you share.  See you next week!

     

  • Using Advanced Mapping in ArcGIS Preview

    Using Advanced Mapping in ArcGIS Preview

    In the September 2016 release of PowerBI, Microsoft introduced a new visual called the ArcGIS Maps preview.  For more information on the maps integration you can read the following post from Microsoft.  This tutorial will review how to load data using Latitude and Longitude data and map those points on the ArcGIS map.

    First, we need to open PowerBI Desktop and then we will load some data.  The version of PowerBI Desktop for this tutorial is 2.39.4526.362 64-bit (September, 2016).  You can download the latest version of the software here.

    On the Home ribbon click on the Get Data button and from the Get Data window select Blank Query.  Click Connect to proceed.

    Now you will be in the Query Editor, click on the View ribbon and select the Advanced Editor button.  The Advanced Editor will now open.

    Enter the following code into the Advanced Editor: (you can copy and paste the code directly from this site)  Click Done to load the data.

    let
     Source = Excel.Workbook(Web.Contents("https://powerbitips03.blob.core.windows.net/blobpowerbitips03/wp-content/uploads/2016/09/Locations.xlsx"), null, true),
     Locations_Table = Source{[Item="Locations",Kind="Table"]}[Data],
     #"Changed Type" = Table.TransformColumnTypes(Locations_Table,{{"Event", type text}, {"Attenders", Int64.Type}, {"Zip", Int64.Type}, {"Latitude", type number}, {"Longitude", type number}})
    in
     #"Changed Type"

    Note: this will load an excel file that is hosted on PowerBI.Tips, so make sure you have an internet connection.

    Load Map Data
    Load Query

    Re-name your query to Map Data and then on the Home ribbon click Close & Apply.

    Load Map Data In PBI
    Load Map Data In PBI

    Before working on this tutorial, you will want to make sure you have enabled the ArcGIS map which is in preview.

    Click the Menu button to open up the menu options.

    PBI Menu Button
    PBI Menu Button

    This will expose the menu.  With the menu open click on Options and Settings and then click on Options.

    Selecting Options
    Selecting Options

    Once the Options menu is open, click on Preview Features and then make sure the ArcGIS Maps for PowerBI preview feature is check.  Then click OK to close the options menu.

    Options Menu
    Options Menu

    You should now see a new bright blue icon listed in the Visualizations window.

    ArcGIS Maps Icon
    ArcGIS Maps Icon

    Click on the ArcGIS visualization and then add the following following columns of data from the Fields window into the visual.

    Fields for ArcGIS Map
    Fields for ArcGIS Map

    OK, Wow, seems like a normal map.  So, why all the hype?  Well, unlike other mapping visualizations, this map enhances the selection methods for points on a map.

    By clicking on the square with the black mouse arrow (highlighted with a green box here because the selection tool for the visual uses a red box)  You can then click drag a red box across the map to select multiple geographical points on the map.

    Highlighting Points on Map
    Highlighting Points on Map

    Selecting points on the map will filter other visuals on the page.

    Add a Table visual with the following fields:

    Table Visual Fields
    Table Visual Fields

    Now click the Multi-Select button and highlight some points on the map.

    Multi-Select Button
    Multi-Select Button

    Notice how only the selected points are highlighted on the map and the table filters to only those points.

    To enhance the map further click the In-Focus Edit Mode button.

    In-Focus Edit Mode
    In-Focus Edit Mode

    Now, the map editor opens.  This allows you to change the basemap view, the theme of the map, symbols on the map and adds other data to enhance the coloring of the map.

    Click on the Basemap button and then select the Dark Gray Canvas.  We have turned the map in to a sort of night mode.

    Basemap Change
    Basemap Change

    Have fun here and explore a couple of the other map types.

    Next Click on the Map Theme then click on the Heat Map.  Alright, this is getting pretty cool.

    Heat Map Selection
    Heat Map Selection

    In the next section Symbol Style you can change the properties of the points on the map.  For the heat map you can change the Transparency and the Area of Influence of the points.  Each map theme, Location, Heat Map, Size, and Clustering have different Symbol Style properties.  So you might want to select a couple different Map Themes and try adjusting the Symbol Styles to see how they change.

    Now finally, the best part of the ArcGIS mapping, the Reference Layer.  This will blow your mind!

    Click the Reference layer button then select a layer to add from the Demographics tab.  For this example, I chose the USA Average Household Income.

    Household Income Layer
    Household Income Layer

    To return to the Report click the Back to Report button in the upper left hand corner of the page view.

    Back to Report
    Back to Report

    The layer feature is by far the most helpful part of this tool.  Imagine the time required to collect all that regional demographics data, model it and then to apply it to the mapping visual.  The ArcGIS mapping tool is quite impressive.

    One other note before we leave.  Now that you are back on the report level view.  Use your mouse scrolling wheel and zoom in and out on the map visual.  Notice the closer you zoom into the data points the more detailed the regional views become. See comparison below:

    Zoomed Views
    Zoomed Views

    Thanks for following along.  Remember to share if you liked this tutorial.  See you next week.

  • HexBin Plot using R

    HexBin Plot using R

    Continuing on the theme with R this month, this week tutorial will be to design a hexagonal bin plot.  At first you may say what in the world is a hexagonal bin plot.  I’m glad you asked, behold a sweet honey comb of data:

    Hexbin Plot
    Hexagonal Bin Plot

    The hexagonal bin plot looks just like a honey comb with different shading.   In this plot we have a number of data points with are graphed in two dimensions (Dimension 1, x-axis and Dimension 2, y-axis).  Each hexagon square represents a collection of points.  Now, if we plot only the points on the same graph we have the following.

    Scatter Plot
    Scatter Plot

    In the scatter plot, it’s difficult to see the concentration of points and if there is any correlation between the first dimension and the second dimension.  By comparison, the hex bin plot counts all the points and plots a heat map.  And, if you ask me the hexagonal bin plot just looks better visually.  To bring this all together, if we overlay the scatter plot on top of the hexagonal bin plot you can see that the higher concentration of dots are in the shaded areas with darker red.

    Plot Overlay
    Plot Overlay

    Cool, now lets build some visuals.  Lets begin.  Tutorial <- Hexagonal Bin Plot   (sorry had to interject a bit of R humor here, ignore if you don’t like code humor)

    The very first step will be to open the R console and to install a new library called HexBin.  Run the following code in the Mircosoft RGui.

    install.packages("hexbin")

    This will load the correct library for use within PowerBI.

    Install hexbin
    Install hexbin

    Start by opening up PowerBI.  Click on the Get Data button on the home ribbon, then select Blank Query.  In the Query editor click on the View ribbon and click on the Advanced Editor.  Enter the following query into the Advanced Editor:

    let
     Source = Csv.Document(Web.Contents("https://powerbitips03.blob.core.windows.net/blobpowerbitips03/wp-content/uploads/2016/09/Hexabin-Data.csv"),[Delimiter=",", Columns=3, Encoding=1252, QuoteStyle=QuoteStyle.None]),
     #"Promoted Headers" = Table.PromoteHeaders(Source),
     #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"SampleID", Int64.Type}, {"Xvalues", type number}, {"Yvalues", type number}})
    in
     #"Changed Type"

    This query loads a csv file of data into PowerBI.

    Note:  For more information on how to open and copy and paste M language into the Advanced Editor you can follow this tutorial, which will walk you though the steps.

    After the clicking Done in the Advanced Editor the data will load.  Next rename the query to Hexabin Data and then on the Home ribbon click Close & Apply.

    Save Query
    Save Query

    Next click on the R visual in the Visualizations bar on the right side of the screen.  There will likely be a pop up warning you about enabling R Scripts.  Click Enable to activate the R script editor.  With the R script visual selected on the page add the following columns to the Values field selector.

    R Visual Fields
    R Visual Fields

    Notice that the R visual is blank at this time.  Next add the following R code in the R script editor window.  This will tell PowerBI Desktop to load the ggplot2 library and define all the parameters for the plot.  I’ve added comments to the code using # symbols.

    library(ggplot2) #load ggplot2 package
    
    # define the data inputs to ggplot
     # set data for x and y values x=, and y=
     # set the min and max for both the x and y axis, xmin=, xmax=, ymin= and ymax=
     ggplot(dataset, aes(x=Xvalues,y=Yvalues, xmin=40, xmax=90, ymin=10, ymax=30)) +
    
    # define the color of the outline of the hexagons with color=c()
     # using c(#"809FFF") allows for the usage of hexadecimal color codes
     stat_binhex(bins=15, color=c("#D7DADB")) +
    
    # set the graph theme to classic, provides a white background and no grid lines
     # Change font size to 18 by using base_size = 18
     theme_classic(base_size=18) +
    
    # Apply lables to the graph for x and y
     labs(x = "Dimension 1", y = "Dimension 2")+
    
    # change the gradient fill to range from grey to Red
     scale_fill_gradient(low = "grey", high = "red")

    Click the run button and the code will execute revealing our new plot.

    R Script Code
    R Script Code

    One area of the code that is interesting to change is the section talking about the number of bins.  In the code pasted above the code states there are 15 bins.

    stat_binhex(bins=15, color=c("#D7DADB")) +

    Try increasing this number and decreasing this number to see what happens with the plot.

    Five Bins
    Five Bins

    stat_binhex(bins=5, color=c("#D7DADB")) +

    Thirty Bins
    Thirty Bins

    stat_binhex(bins=30, color=c("#D7DADB")) +

    Well that is it.  Thanks for reading through another tutorial.  I hope you had fun.

    Want to see more R checkout the Microsoft R Script Showcase.  If you want to download the PBIX file used to create this visual you can download the file here.

    If you want to learn more about R and the different visuals you can build within R check out this great book which helped me learn plotting with R.