locked
How to display our own percentage in google pie chart RRS feed

  • Question

  • User2101416554 posted

    The below is my code which is working fine ...

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleChart.aspx.cs" Inherits="GoogleChart" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    
      
    
    </head>
    <body>
        <form id="form1" runat="server">
       
          <center>
        <asp:DropDownList ID="DrpMonth" runat="server" >
       
            <asp:ListItem Text="Finland" Value="Finland" ></asp:ListItem>
            <asp:ListItem Text="Brazil" Value="Brazil" Selected="True"></asp:ListItem>
            <asp:ListItem Text="USA" Value="USA"></asp:ListItem>
            <asp:ListItem Text="Italy" Value="Italy"></asp:ListItem>
            <asp:ListItem Text="Germany" Value="Germany"></asp:ListItem>
        </asp:DropDownList>
    </center>
    
    <div id="chart" style="width: 900px; height: 500px;">
    </div>
    
    
       
    
    
        </form>
    
       
    
     
      <script src="https://www.google.com/jsapi" type="text/javascript"></script>
    
     
      <script src="jquery.min.js" type="text/javascript"></script>
      <script src="code.min.js" type="text/javascript"></script>
    
    
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Web.Services;
    using System.Configuration;
    using System.Data.SqlClient;
    
    public partial class GoogleChart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        public class trafficSourceData
        {
            public string label { get; set; }
            public string value { get; set; }
            public string color { get; set; }
            public string hightlight { get; set; }
        }
    
        [WebMethod]
        public static List<object> GetChartData(string country)
        {
            string query = "SELECT ShipCity, COUNT(orderid) TotalOrders,count(orderid) * 100.0 / (select count(*) from Orders WHERE ShipCountry = @Country) as Per FROM Orders WHERE ShipCountry = @Country GROUP BY ShipCity";
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            List<object> chartData = new List<object>();
            chartData.Add(new object[] { "ShipCity", "Per " });
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Country", country);
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            chartData.Add(new object[] { sdr["ShipCity"], sdr["Per "] });
                        }
                    }
                    con.Close();
                    return chartData;
                }
            }
        }
    
    }

    Js

    <script type="text/javascript">
    
              
            $(document).ready(function () { 
    
               
                var a = $("#DrpMonth option:selected").val();
    
    
                $.ajax({
                    type: "POST", url: "GoogleChart.aspx/GetChartData", data: "{country: '" + a + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (t) { var o = google.visualization.arrayToDataTable(t.d), e = new google.visualization.PieChart($("#chart")[0]); e.draw(o, { title: a + " Distribution", is3D: !0 }); var n = 0, r = setInterval(function () { n += 1, o.setValue(0, 1, n), o.setValue(1, 1, 100 - n), e.draw(o, { title: a + " Distribution", is3D: !0, chartArea: { left: "5%", width: "90%", height: 350 }, slices: { 1: { offset: .2 }, 2: { offset: .15 }, 3: { offset: .16 }, 4: { offset: .12 } } }), n > 74 && clearInterval(r) }, 30) }, failure: function (a) { alert(a.d) }, error: function (a) { alert(a.d) }
                })
    
    
                
    
            });
    
             
         
            google.load("visualization", "1", { packages: ["corechart"] }),
                google.setOnLoadCallback(function () { $("#DrpMonth").on("change", function () { drawChart() }) });
    
             
    
            function drawChart() {
    
    
    
                var a = $("#DrpMonth option:selected").val();
    
                $.ajax({
                    type: "POST", url: "GoogleChart.aspx/GetChartData", data: "{country: '" + a + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (t) { var o = google.visualization.arrayToDataTable(t.d), e = new google.visualization.PieChart($("#chart")[0]); e.draw(o, { title: a + " Distribution", is3D: !0 }); var n = 0, r = setInterval(function () { n += 1, o.setValue(0, 1, n), o.setValue(1, 1, 100 - n), e.draw(o, { title: a + " Distribution", is3D: !0, chartArea: { left: "5%", width: "90%", height: 350 }, slices: { 1: { offset: .2 }, 2: { offset: .15 }, 3: { offset: .16 }, 4: { offset: .12 } } }), n > 74 && clearInterval(r) }, 30) }, failure: function (a) { alert(a.d) }, error: function (a) { alert(a.d) }
                })
    
    
            }
    
             
    
    
    
    
           
                 
      
    
        </script>

    The above query is working fine. The Google chart shows different percentage where i would like to display my per column value.

    Monday, January 13, 2020 5:38 AM

All replies

  • User-1038772411 posted

    Hello umerfaiz123,

    Checked your problem but can't identify your percentage so that assign direct value to data.

    Make sure that you can pass the total percentage as 100.
    If sum of all the values is 100 then and then only it shows perfect percentage otherwise it might calculate based on 360 which is circle's degree(Angle).


    The below code for the aspx

    <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
          </script>
          <script type = "text/javascript">
              google.charts.load('current', { packages: ['corechart'] });               
          </script>
         
        
        <div id = "googlePieChart" style = "width: 550px; height: 400px; margin: 0 auto">
          </div>
    
    
          <script type = "text/javaScript">
             function drawGooglePieChart() {            
                var chartData = new google.visualization.DataTable();
                chartData.addColumn('string', 'Name');
                chartData.addColumn('number', 'Percentage');
                chartData.addRows([
                   ['A', 30.0],
                   ['B', 18],
                   ['C', 10],
                   ['D', 14.0],
                   ['F', 28]
                 ]);
    
                //  chartData.addRows([
                //   ['A', 40.0],
                //   ['B', 28],
                //   ['C', 20],
                //   ['D', 24.0],
                //   ['F', 38]
                //]);
                   
                var chartoptions = {
                   'title':'Sample Google pie chart',
                   'width':500,
                    'height': 350,
                };
    
                
                var chartDetails = new google.visualization.PieChart(document.getElementById('googlePieChart'));
                chartDetails.draw(chartData, chartoptions);
             }
             google.charts.setOnLoadCallback(drawGooglePieChart);
          </script>
    </asp:Content>

    The commented line in code is data, whose sum is not 100, more than 100 so once you pass in code as data then percentage will be changed. Same way you pass less total then 100 then also it might change the percentage.

    If you still facing any issue please let us know.

    Thanks.

    Monday, January 13, 2020 10:54 AM
  • User1535942433 posted

    Hi umerfaiz123@outlook.com,

    The above query is working fine. The Google chart shows different percentage where i would like to display my per column value.

    Accroding to your description and codes,I creat a test and it could display the percentage of every bar.

    Could you tell us what you mean about the column value?Do you want to display percentage and city name in every bar?

    Best regards,

    Yijing Sun

    Tuesday, January 14, 2020 3:32 AM
  • User2101416554 posted
    This is my db data chart value ...
    
    ShipCity	Per
    Finland	60
    Finland	14
    Finland	10
    Finland	5
    Finland	3
    Finland	2
    Finland	2
    Finland	0
    

    But the chart shows percentage as 61.5,20.5,8.2,4.1,2.5

    Saturday, January 18, 2020 10:13 AM
  • User-158764254 posted

    when you pass options to your chart draw method, you need to include this in your options:

    pieSliceText: 'value'

    Saturday, January 18, 2020 12:42 PM
  • User2101416554 posted
    How to add pieslicetext ?
    Sunday, January 19, 2020 4:43 PM
  • User-158764254 posted

    https://stackoverflow.com/questions/22361426/google-pie-chart-show-both-percentage-and-values

    var options = {
       pieSliceText: 'value'
    };
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);

    Sunday, January 19, 2020 4:49 PM