I am trying to build a simple plotly dash app in python which uses an R script to generate an image of a chart and displays it in the app. I am using py2rpy to convert the pandas data to R data before passing to my R script to generate the chart. This works find outside of the plotly dash script but not within it rather throwing an error depending on the version of code I use either:
NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'str'>'
NotImplementedError: Conversion rules for
rpy2.robjectsappear to be missing. Those rules are in a Python contextvars.ContextVar. This could be caused by multithreading code not passing context to the thread.
Original Code:
@callback(
Output('figure-1-graph-controls', "figure"),
Input('figure-1-drop-down-selection', "value"),
Input('figure-2-drop-down-selection', "value"),
)
def update_figure1(col_chosen1, col_chosen2):
subset = df[(df['col1']==col_chosen1) & (df['col2']==col_chosen2)]
r_data = ro.conversion.py2rpy(subset)
r_set = r_function(r_data)
converted = ggplot2.ggplot2_conversion(r_set)
png_image = image_png(converted)
return png_image
I have tried adding the r context within the Dash/Plotly plot function like so:
ro.r['source']('Chart.R')
r_function = ro.globalenv['generate_chart']
pandas2ri.activate()
with localconverter(ro.default_converter + pandas2ri.converter):
r_data = ro.conversion.py2rpy(subset)
r_set = r_function(r_data)
converted = ggplot2.ggplot2_conversion(r_set)
Both work outside the dash app code but not when used inside. I have also tried calling the py2rpy conversion using a function but same issue occurs.