简体   繁体   中英

ASP.NET Stacked Bar Chart Show Totals At Top Of Stack

我有一个堆叠的条形图,其中包含多个系列,我想在每个堆叠列的顶部以标签的形式显示堆叠的总数。

Set the series' up in order with the 'total' series having a transparent color and not shown in the legend

  TgtChart.Series.Add("Series1");
  TgtChart.Series["Series1"].Color = System.Drawing.Color.LightGreen;
  TgtChart.Series.Add("Series2");
  TgtChart.Series["Series12"].Color = System.Drawing.Color.HotPink;
  TgtChart.Series.Add("SeriesTotal");
  TgtChart.Series["SeriesTotal"].Color = System.Drawing.Color.Transparent;
  TgtChart.Series["SeriesTotal"].IsVisibleInLegend = false;

Add your series points with the desired X-axis label and Y-axis value while keeping track of the highest total value - it is needed later.

  TgtChart.Series["Series1"].Points.AddXY("XIncrement1", YValueSeries1);
  TgtChart.Series["Series2"].Points.AddXY("XIncrement1", YValueSeries2);
  TgtChart.Series["SeriesTotal"].Points.AddXY("XIncrement1"], SeriesTotal);
  if (maxTot < SeriesTotal) maxTot = SeriesTotal;

Go through all of the points in the total series and set the label equal to the Y value, then set the Y value to the same one for all points - I used a fraction of the highest total so all total labels will have the same offset. The label always goes in the middle of the (transparent) bar, so you might need to play with the fraction to get a good appearance for various stacks/totals. I didn't want to show labels if the stack total was zero. There is surely a cleaner way to make sure the constant SeriesTotal stack height was not less than 1.

foreach (DataPoint dp in TgtChart.Series["SeriesTotal"].Points)
{
  if (TgtChart.Series[ii].Name == "Total RTAs")
  {
    dp.Label = dp.YValues[0].ToString();
    dp.YValues[0] = (int)(maxTot / 20) != 0 ? (int)(maxTot / 20): 1;
  if (dp.YValues[0] != 0)
    dp.IsValueShownAsLabel = true;
  else
    dp.IsValueShownAsLabel = false;
}
            Chart1.Series.Add("Total")

            Chart1.Series("Total").ChartType = SeriesChartType.Point
            Chart1.Series("Total").MarkerSize = 5  'change this to 0 if you don't want a marker at the top  of the col.
            Chart1.Series("Total").MarkerStyle = MarkerStyle.Diamond
            Chart1.Series("Total").IsValueShownAsLabel = True


            For k As Integer = 0 To 1 'if there are 2 columns to add
                Dim total As Double = 0
                For j As Integer = 0 To 1
                    total += Chart1.Series(j).Points(k).YValues(0)
                Next
                Chart1.Series("Total").Points.AddY(total)
            Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM