Search code examples
rformattingpie-chartplotly

How to change format values in a Pie Chart made by plotly (in R)


First of all thank you for spending a little bit of your time helping me to solve this issue.

I am getting started in plot_ly through R and I am struggling when trying to change the format of the values of my Pie Chart (I want them to be showed in the plot as currency "$" format).

So far my code looks like:

data <- data.frame(Level = c("Receipt","Disbursement"),Amount = c(1000,2000))

name_dataset <- "Overview"

plot_ly(data=data, labels = Level, values = Amount, type = "pie", textinfo= "label+percent", 
        hoverinfo = "label+percent+value", outsidetextfont = list(color = "white")) %>% layout(title = paste0(paste(unlist(strsplit(name_dataset,"_")),collapse = " ")))

Thank you for your help!


Solution

  •     var text = [15588, 16787, 27778].map(function (v, i) {
          return currencyFormatterForUI(v) //format here
        });
    
        var chartObj = {
            header: 'New Backlog',
            description: 'Total Value of Recently Added (Last 30 Days) Backlog by Issue Type',
            type: 'chart',
            id: 'div4',
            layout: {
              margin: {
                autoexpand: true,
                r: 25,
                t: 20,
                b: 20,
                l: 25
              },
              legend: {
                'orientation': 'h',
                xanchor: 'center',
                yanchor: 'top',
                y: -0.1, // play with it
                x: 0.5 // play with it
              },
            },
            data: [{
              values: [15588, 16787, 27778],
              labels: ['Bug', 'Improvement', 'Story'],
              text: text,
              type: 'pie',
              textinfo: 'label+text',
              hoverinfo: 'label+text+percent'
            }],
          };
          
          var myPlot = document.getElementById('div4');
          Plotly.plot(myPlot, chartObj);
    
          function currencyFormatterForUI(value) {
            const formatter = new Intl.NumberFormat('en-US', {
              style: 'currency',
              currency: 'USD',
              minimumFractionDigits: 0,
              maximumFractionDigits: 0
            });
            return formatter.format(value || 0);
          }
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        <div id="div4"></div>