Fehnraal
Fehnraal

Reputation: 40

Power Bi custom R visual (PBIVIZ)

**EDIT; For simplicity's sake, I will give an example of what I'm trying to do. I need to softcode my plotting. Below is hardcoded.

  p <- ggplot(data = Thisismydata, aes(x = thisismyX, fill = thisismyFill)) +
    geom_bar(position = "dodge")
  w = ggplotly(p)
  w =as_widget(w)
}

I need something dynamic so I don't HAVE to use hardcoded columns.All I have to compare it to is the pseudo-Python version, like so;

  p <- ggplot(data = dataset, aes(x = dataset.iloc[:,1], fill = dataset.iloc[:,2])) +
    geom_bar(position = "dodge")
  w = ggplotly(p)
  w =as_widget(w)
}

I need to declare these as the positions of the columns in my fields, not by name. These will be swapped around a lot and I can't have errors pop up because someone used an undeclared name in their value/column.**

I'm creating a visual for Power BI and I'm stuck. At the very beginning. This is odd. I have made visuals in Typescript and Python, but I don't think I have ever gotten stuck on something this early on. I can't seem to find any good and up to date resources for R custom visuals in Power BI, so I'm stuck using old YouTube videos and 3 year old Github repositories. If anyone could help me out on this with some updated information, I would be incredible grateful. My issue is as below;

I've started building an R visual based on a YouTube video from three years ago. That's likely my first mistake. This is also a PBIVIZ, not the script window in Power BI. Inside of my script.r file I have this

source('./r_files/flatten_HTML.r')

############### Library Declarations ###############
libraryRequireInstall("ggplot2");
libraryRequireInstall("plotly")
####################################################

################### Actual code ####################
g = plot_ly(x = Values[,1], y = Values[,2], text = paste("z:", Values[,3]),mode = "markers", color = Values[,3], size = Values[,1])
####################################################

############# Create and save widget ###############
p = ggplotly(g);
internalSaveWidget(p, 'out.html');
####################################################```

This doesn't seem to do anything. It says my Values object doesn't exist... but I am following it verbatim according to their tutorial. I'm not sure how this works, but in the script editor built inside of Power BI, you could declare each field using indexing. I can't remember the proper syntax, so I will use Python as an example. In Python, if you needed to do something with the first field on the visual, it would be dataset.iloc[,0]. I'm -assuming- that's what's going on here, since they didn't really explain it. It looks like some sort of indexing... My capabilities is all funky for now from a previous build I was working on, but that isn't really a big deal. I can revert that to default and work on that later. For now I would just like to get something to plot.

My end game is just a line chart.

Can anyone tell me what I'm doing wrong? These fields also need to be dynamic since they could change depending on what the user wants to throw in there, so I'm trying to avoid hard-coding fields in there by name.

Error log

Feedback Type:
Frown (Error)

Timestamp:
2019-09-09T16:03:19.3159296Z

Local Time:
2019-09-09T11:03:19.3159296-05:00

Session ID:
#####

Release:
August 2019

Product Version:
2.72.5556.801 (19.08) (x64)

Error Message:
R script error.
Loading required package: XML
Loading required package: htmlwidgets
Loading required package: ggplot2
Loading required package: plotly

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout

Error in plot_ly(x = Values[, 1], y = Values[, 2], text = paste("z:",  : 
  object 'Values' not found
Execution halted


Stack Trace:
Microsoft.PowerBI.ExploreServiceCommon.ScriptHandlerException: R script error.
Loading required package: XML
Loading required package: htmlwidgets
Loading required package: ggplot2
Loading required package: plotly

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout

Error in plot_ly(x = Values[, 1], y = Values[, 2], text = paste("z:",  : 
  object 'Values' not found
Execution halted
 ---> Microsoft.PowerBI.Scripting.R.Exceptions.RScriptRuntimeException: R script error.
Loading required package: XML
Loading required package: htmlwidgets
Loading required package: ggplot2
Loading required package: plotly

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout

Error in plot_ly(x = Values[, 1], y = Values[, 2], text = paste("z:",  : 
  object 'Values' not found
Execution halted

   at Microsoft.PowerBI.Scripting.R.RScriptWrapper.RunScript(String originalScript, Int32 timeoutMs)
   at Microsoft.PowerBI.Client.Windows.R.RScriptHandler.GenerateVisual(ScriptHandlerOptions options)
   --- End of inner exception stack trace ---
   at Microsoft.PowerBI.Client.Windows.R.RScriptHandler.GenerateVisual(ScriptHandlerOptions options)
   at Microsoft.PowerBI.ExploreServiceCommon.ScriptVisualCommandFlow.RunInternal(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
   at Microsoft.PowerBI.ExploreServiceCommon.ScriptVisualCommandFlow.Run(Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.TransformDataShapeResult(QueryCommand transformCommand, SemanticQueryDataShapeCommand command, Stream dataShapeResultStream, QueryBindingDescriptor& bindingDescriptor)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ExecuteDataQuery(IQueryResultDataWriter queryResultDataWriter, EngineDataModel engineDataModel, DataQuery query, Int32 queryId, ServiceErrorStatusCode& serviceErrorStatusCode, CancellationToken cancelToken)
   at Microsoft.PowerBI.ExploreHost.SemanticQuery.ExecuteSemanticQueryFlow.ProcessAndWriteSemanticQueryCommands(IQueryResultsWriter queryResultsWriter, IList`1 queries, HashSet`1 pendingQueriesToCancel, EngineDataModel engineDataModel)

Invocation Stack Trace:
   at Microsoft.Mashup.Host.Document.ExceptionExtensions.GetCurrentInvocationStackTrace()
   at Microsoft.Mashup.Client.UI.Shared.StackTraceInfo..ctor(String exceptionStackTrace, String invocationStackTrace, String exceptionMessage)
   at Microsoft.PowerBI.Client.Windows.ErrorHostService.GetErrorDetails(ShowErrorDialogArgs args)
   at Microsoft.PowerBI.Client.Windows.ErrorHostService.<>c__DisplayClass2_0.<<ShowErrorDialog>b__0>d.MoveNext()
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
   at Microsoft.PowerBI.Client.Windows.ErrorHostService.<>c__DisplayClass2_0.<ShowErrorDialog>b__0()
   at Microsoft.Mashup.Host.Document.SynchronizationContextExtensions.<>c__DisplayClass1_0`1.<SendAndMarshalExceptions>b__0()
   at Microsoft.Mashup.Host.Document.SynchronizationContextExtensions.<>c__DisplayClass0_1.<SendAndMarshalExceptions>b__0(Object null)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
   at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
   at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
   at Microsoft.Mashup.Client.UI.Shared.WebDialogs.WebDialog.<>n__0(IWindowHandle owner)
   at Microsoft.Mashup.Client.UI.Shared.WindowManager.ShowModal[T](T dialog, Func`1 showModalFunction)
   at Microsoft.PowerBI.Client.Program.<>c__DisplayClass4_0.<Main>b__1()
   at Microsoft.PowerBI.Client.Windows.IExceptionHandlerExtensions.<>c__DisplayClass3_0.<HandleExceptionsWithNestedTasks>b__0()
   at Microsoft.Mashup.Host.Document.ExceptionHandlerExtensions.HandleExceptions(IExceptionHandler exceptionHandler, Action action)
   at Microsoft.PowerBI.Client.Program.Main(String[] args)


OS Version:
Microsoft Windows NT 10.0.17134.0 (x64 en-US)

CLR Version:
4.7 or later [Release Number = 461808]

Peak Virtual Memory:
38.3 GB

Private Memory:
445 MB

Peak Working Set:
673 MB

IE Version:
11.950.17134.0

User ID:#####

Workbook Package Info:
1* - en-US, Query Groups: 0, fastCombine: Disabled, runBackgroundAnalysis: True.

Telemetry Enabled:
True

AS Live Connection:
True

Performance Trace Logs:
C:\Users\MYNAME\Microsoft\Power BI Desktop Store App\PerformanceTraces.zip

Enabled Preview Features:
PBI_userFavoriteResourcePackagesEnabled

Disabled Preview Features:
PBI_shapeMapVisualEnabled
PBI_SpanishLinguisticsEnabled
PBI_NewWebTableInference
PBI_showIncrementalRefreshPolicy
PBI_qnaLiveConnect

Disabled DirectQuery Options:
TreatHanaAsRelationalSource

Cloud:
GlobalCloud

DPI Scale:
100%

Supported Services:
Power BI

Formulas:


section Section1;

Upvotes: 2

Views: 1506

Answers (2)

r-q
r-q

Reputation: 63

This worked for me in a similar situation:

libraryRequireInstall( "ggplot2" )
libraryRequireInstall( "plotly" )

x_name <- names( Values )[ 1 ]
y_name <- names( Values )[ 2 ]
g <- ggplot( Values, aes( x = .data[[ x_name ]], y = .data[[ y_name ]] ) ) +
    geom_point()
ggplotly( g )

Upvotes: 0

Amit Kohli
Amit Kohli

Reputation: 2950

welcome to the community!

R in Power BI is a bit annoying.

  1. It's not going to source that file in because it might not know where your get_wd(). Try putting your whole path, or even better, upload that somewhere online and see if that'll work, OR import the data into PowerBI and read it from there.
  2. you'll have to make sure that THE R INSTALLATION THAT POWER BI IS USING has both ggplot2 and plotly installed. Make sure it's the same exact version of R, or it won't work.

Try those 2, if it doesn't, post the error it gives you and we'll take it from there.

Upvotes: 0

Related Questions