如何更改饼图中的格式值(在R中)

时间:2016-05-26 13:09:12

标签: r formatting pie-chart plotly

首先,感谢您花一点时间帮助我解决这个问题。

我从plot_ly通过R开始,当我试图更改我的饼图值的格式时我正在努力(我希望它们在图中显示为货币" $& #34;格式)。

到目前为止,我的代码如下:

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 = " ")))

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

你在寻找这样的东西:

data$AmountB <- prettyNum(data$Amount, big.mark=",",scientific=FALSE) #EDIT
data$AmountB <- paste(data$AmountB, "$", sep="")
plot_ly(data=data, labels = Level, values = Amount, type = "pie", textinfo= "text", text=AmountB,hoverinfo = "text", outsidetextfont = list(color = "white")) %>% 
layout(title = paste0(paste(unlist(strsplit(name_dataset,"_")),collapse = " ")))

enter image description here

答案 1 :(得分:1)

&#13;
&#13;
    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);
      }
&#13;
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <div id="div4"></div>
&#13;
&#13;
&#13;