0

I'm very new to R and beginner level at programming in general, and trying to figure out how to get hovertext in plotly to display a Japanese string from my dataframe. After venturing through character encoding hell, I've got things mostly worked out but am getting stuck on a single point: Getting the Japanese string to display in the final plot.

plot_ly(df, x = ~cost, y = ~grossSales, type = "scatter", mode = "markers",
    hoverinfo = "text",
    text = ~paste0("Product name: ", productName,
                    "<br>Gross: ", grossSales, "<br> Cost: ", cost, 
                    )
    ) 

The problem I encounter is that using 'productName' returns the Japanese string from the dataframe, which causes the plot to fail to render. DOM Inspector's console shows JSON encountering issues with the string (even though it's just encoded in UTF-8).

Using toJSON(productName), I am able to render the table, however this renders the hover textbox with the full information of the productName column (e.g., ["","Product1","Product2","Product3"...]). I only want the name of that specific product; just as 'grossSales' and 'cost' only return one the data specific to that product at each point on the plot.

Is there a way I can execute toJSON() only on each specific instance of 'productName'? (i.e., output should be "Product1" with JSON friendly string format) Alternatively, is there a way I can have plotly read the list output and select only the correct productName?

sinaraheneba
  • 781
  • 4
  • 18

1 Answers1

0

Stepping away from the problem to continue studying other things, I found a partial solution in using a for-loop:

productNames <- NULL
for (i in 1:nrow(df))
{
    productNames <- c(productNames, toJSON(df[i, "productName"]))
}
df$jsonProductNames <- productNames

Using the jsonProductNames variable within plotly, the graph renders and displays only the name for each product! The sole issue remaining is that it is displayed with the JSON [""] formatting around each product's name.

Update:

I've finally got this working fully how I want it. I imagine there are more elegant solutions, and I'd still be interested to learn how to achieve what I originally was looking at if possible (run a function on a variable within R for each time it is encountered in a loop), but here is how I have it working:

colToJSON <- function(df, colStr)
{
    JSONCol <- NULL
    for (i in 1:nrow(df))
    {
        JSONCol <- c(JSONCol, toJSON(df[i, colStr]))
    }
    JSONCol <- gsub("\\[\"", "", JSONCol)
    JSONCol <- gsub("\"\\]", "", JSONCol)
    return(JSONCol)
}

df$jsonProductNames <- colToJSON(df, "productName")
sinaraheneba
  • 781
  • 4
  • 18