Creating and Using R Visuals in Power BI

In this tutorial, we will show how to create and use R visuals in Power BI.  Let us walk you through everything you need to know to create, publish, and work with R visuals in Power BI.

Creating and Using R Visuals in Power BI width=

 

R is one of the most powerful languages for statistical analysis and data visualization. R visuals let you use R scripts to generate custom charts inside Power BI. You can create custom, advanced charts and plots that go beyond standard Power BI visuals, such as correlation plots, heatmaps, advanced forecasting visualizations, and specialized statistical graphics. Power BI lets you harness that power directly inside your reports.

In this tutorial, we will show you how to create and use R visuals in Power BI. Let us walk you through everything you need to know to create, publish, and work with R visuals in Power BI.

Requirements for Using R Visuals

R visuals are charts and graphics generated by R scripts embedded within Power BI. They allow you to go beyond Power BI’s built-in visuals to produce advanced analytics outputs like correlation matrices, custom statistical plots, forecasting charts, and more, all using R’s rich ecosystem of packages.

Before creating R visuals, ensure the following requirements are met.

  • Download and install R from the official website
  • Power BI Desktop detects and enables R automatically once it is installed
  • Any R packages your script needs are installed locally

Power BI Desktop can use any locally installed R package. You can install the packages you need for use in Power BI Desktop on your own.

Remember: R visuals can only be created in Power BI Desktop and then published to the Power BI service. The Power BI service supports viewing and interacting with visuals created with R scripts, but authoring happens only in Desktop.

Step 1: Enabling R in Power BI

If R is not detected automatically after installation, you can enable it manually.

  • Open Power BI Desktop and configure R
  • Go to the File tab >> select Options and settings >> select Options
  • Select R scripting from GLOBAL
  • Choose your installed R home directory
  • Or add R visuals in Power BI >> click the Settings icon >> select R scripting and its directory
  • Click OK

2. Creating and Using R Visuals in Power BI

Power BI will now be able to execute R scripts.

Step 2: Adding R Visuals in Power BI

Importing Your Data:

  • Load data into Power BI from Excel, a database, a web source, or any supported connector
    • Go to the Home tab >> select your data source
  • The fields you bring into the R visual’s field well become the dataset your script operates on

Adding an R Visual to Your Report:

  • In the Visualizations pane, click the R visual icon (it looks like a stylized “R”)
  • A placeholder appears on the canvas, and an R script editor opens at the bottom of the screen
  • If this is your first time, a dialog appears: Enable script visuals >> click Enable

1. Creating and Using R Visuals in Power BI

Adding Fields:

  • Drag fields into the Values section of the R visual
  • Power BI automatically creates a data frame called dataset
  • This data frame contains the selected fields

10. Creating and Using R Visuals in Power BI

That security warning matters: Microsoft explicitly warns that R scripts can contain privacy or security risks, so you should only enable them when you trust the source or have reviewed the script.

Step 3: Writing Your R Script

Once the R visual is on the canvas and fields are assigned, an R script editor appears. This is where you write the code that draws the chart. Power BI automatically passes your selected data as a data frame called dataset. You can write R code using standard plotting libraries such as base R, ggplot2, lattice, and corrplot.

Let’s create a box plot to summarize the distribution of a numeric variable across different groups. For each category, it shows the minimum, maximum, median, and spread of values, and it highlights any outliers as individual dots. It reveals the full picture of how profit varies within each category.

  • Drag Category and Profit fields into the Values area

R Script:

library(ggplot2)

ggplot(dataset, aes(x = Category, y = Profit, fill = Category)) +
  geom_boxplot() +
  labs(
    title = "Profit Distribution by Category",
    x = "Category",
    y = "Profit"
  ) +
  theme_minimal() +
  theme(legend.position = "none") # hides the legend since the x-axis already labels each category
  • geom_boxplot(): Draws the box plot; R calculates the statistics (median, IQR, and outliers) automatically.
  • fill = Category: Assigns a different color to each category automatically.
  • theme(legend.position = “none”): Removes the color legend since the x-axis already identifies each category.
  • Outliers: Data points that fall far outside the typical range, shown as individual dots above or below the whiskers.
  • aes(): Maps variables in the dataset to visual properties such as the x-axis, y-axis, and fill color.
  • labs(): Adds the chart title and axis labels.
  • theme_minimal(): Applies a cleaner visual style.

Running the Script:

  • Once you click Run (or the play button in the script editor), the visual renders on the canvas
  • The visual renders using your local R engine
  • If errors occur, check the error message and click See details for the full logs

3. Creating and Using R Visuals in Power BI

  • Final visual:

6. Creating and Using R Visuals in Power BI

Refining and Testing:

  • You can now use this R visual alongside other Power BI visuals in your report

7. Creating and Using R Visuals in Power BI

  • When you apply filters or slicers, the R visual refreshes automatically (up to 150,000 rows)
  • Behavioral Differences: Once you are done, there are a few differences from standard visuals to keep in mind:
    • R visuals cannot show tooltips and cannot be used to filter other visuals
    • R visuals respond to highlighting from other visuals, but you cannot select elements in an R visual to cross-filter other visuals
    • R visuals are refreshed upon data updates, filtering, and highlighting. However, the image itself is not interactive

8. Creating and Using R Visuals in Power BI

Step 4: Exploring R Visual Examples in Power BI

Building a Correlation Matrix

A correlation matrix shows how strongly pairs of numeric variables are related to each other. It answers questions like “Does higher cost lead to higher sales?” or “Are discounts hurting profit?” in a single visual. Instead of building multiple scatter plots one by one, a correlation matrix shows all relationships at a glance.

  • Drag the following fields into the Values area: Total Sales, Profit, Cost, Quantity, and Discount

R Script:

library(corrplot)

cor_matrix <- cor(dataset[, sapply(dataset, is.numeric)], use = "complete.obs")

corrplot(cor_matrix,
  method = "color",      # fills each cell with color instead of circles or numbers
  type = "upper",        # shows only the upper triangle to avoid repetition
  addCoef.col = "black", # prints the correlation number inside each cell
  tl.col = "black",      # sets the axis label color to black
  tl.srt = 45,           # rotates axis labels 45 degrees for readability
  title = "Sales Metrics Correlation Matrix",
  mar = c(0, 0, 2, 0)    # adjusts margins so the title fits
)
  • cor(): R’s built-in function for calculating correlation between variables.
  • sapply(dataset, is.numeric): Filters the dataset to include only numeric columns, since correlation works only on numeric data.
  • use = “complete.obs”: Tells R to ignore rows with missing values instead of throwing an error.

4. Creating and Using R Visuals in Power BI

Creating a Histogram with a Density Curve

A histogram groups your data into ranges (called bins) and shows how many records fall into each range. Adding a density curve on top turns it into a smooth line that shows the overall shape of your data’s distribution.

This visual helps you understand whether your sales values are clustered around a common amount, skewed toward high or low values, or spread out evenly, which is something a simple bar chart or line chart will not tell you.

  • Drag Sales Amount into the Values field

R Script:

library(ggplot2)

ggplot(dataset, aes(x = `Sales Amount`)) +
  geom_histogram(aes(y = after_stat(density)), bins = 30, fill = "steelblue", color = "white") +
  geom_density(color = "red", linewidth = 1) +
  labs(
    title = "Sales Amount Distribution",
    x = "Sales Amount",
    y = "Density"
  ) +
  theme_minimal()
  • geom_histogram(): Draws the histogram bars; bins = 30 controls how many bars are shown (more bins means more detail).
  • aes(y = after_stat(density)): Rescales the histogram’s y-axis to density instead of count so that it matches the density curve’s scale.
  • geom_density(): Draws the smooth curved line over the histogram.
  • fill: Sets the inside color of the bars.
  • color: Sets the border color of the bars.

5. Creating and Using R Visuals in Power BI

Step 5: Publishing to the Power BI Service

Once your report looks the way you want, publish it to the Power BI service.

  • Go to the Home tab >> click Publish
  • Choose a workspace >> click Select

9. Creating and Using R Visuals in Power BI

  • Open the report in the Power BI service, and your R visual will render automatically

R visuals created in Power BI Desktop and then published to the Power BI service can be viewed and filtered like other visuals in a report. However, the rendered R image itself is not directly interactive.

How R Scripts Work in Power BI

  • Data Input: Power BI creates a dataset automatically (data.frame)
    • Maximum of 150,000 rows; excess rows are truncated and a warning is shown
    • Maximum input size of about 250 MB in the visual pipeline
    • Unsupported: Time data type (use Date/Time instead); strings longer than 32,766 characters are truncated
    • Column names used in your script must match the field names passed into the visual
  • Execution:
    • Desktop: Uses your local R installation and locally installed packages
    • Service: Uses a sandboxed cloud R engine that supports approved CRAN packages only, has no internet access, and enforces a 60-second timeout
  • Output: The script must produce a plot (base plot(), ggplot, and so on). Only the last graphical output renders

Supported R Packages:

  • Desktop: Any locally installed package (install via install.packages() or RStudio)
  • Service: Only officially supported CRAN packages. See the full list of R packages
    • No custom or private packages
    • No packages that require internet access during execution
    • Common examples include ggplot2, dplyr, corrplot, plotly (static), and forecast

Limitations of R Visuals

While powerful, R visuals have some limitations.

  • Script Execution Time: R visuals must execute quickly. Large datasets can slow down report performance.
  • Limited Interactivity: Unlike native visuals, R charts are rendered as images.
  • Package Restrictions: In Desktop, only packages installed on the machine running Power BI can be used.
  • Service Limitations: When publishing to the Power BI service:
    • Only supported R packages will run
    • Scripts must follow Power BI security policies

Best Practices for Using R Visuals

To maximize performance and usability, follow these guidelines.

  • Develop and Test in RStudio First: Build your visualization logic outside Power BI first, then paste the working script into Power BI.
  • Use Aggregated Data: Avoid sending huge datasets to R scripts. Use filters or aggregations to reduce row counts.
  • Optimize Scripts: Remove unnecessary computations to reduce execution time.
  • Use Popular R Packages: Use widely supported packages such as ggplot2, dplyr, and tidyr. Also, check the supported packages list before relying on a package in the service.
  • Use the Dataset as the Data Frame Name: Power BI always passes data to this variable.
  • Test Before Publishing: Always test the report in the Power BI service after publishing.

Conclusion

By following the steps above, you can create and use R visuals in Power BI. R visuals provide a powerful extension point for custom plotting and advanced analytical visuals. The workflow is straightforward: install R, add an R visual, assign fields, write the R script, and publish the report. The main things to watch are package support, security prompts, and the row, size, and execution-time limits in Desktop and the service. Although they have some limitations, R visuals are an excellent solution when built-in Power BI visuals are not sufficient.

Get FREE Advanced Excel Exercises with Solutions!

Shamima Sultana
Shamima Sultana

Shamima Sultana, BSc, Computer Science and Engineering, East West University, Bangladesh, has been working with the ExcelDemy project for 4+ years. She has written and reviewed 1000+ articles for ExcelDemy. She has also led several teams with Excel VBA and Content Development works. Currently, she is working as the Technical Content Specialist and analyst and oversees the blogs, forum and YouTube contents. Her work and learning interests vary from Microsoft Office Suites, Google Workspace and Excel to Data... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Close the CTA

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo