• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3507
  • Last Modified:

don't show zero values, chart, c#

I found the following code  to use in my project (to not display zero values):
            //hide label value if zero
            foreach (System.Web.UI.DataVisualization.Charting.Series series in chart.Series)
            {
                foreach (System.Web.UI.DataVisualization.Charting.DataPoint point in series.Points)
                {
                    if (point.YValues.Length > 0 && (double)point.YValues.GetValue(0) == 0)
                    {
                        point.IsValueShownAsLabel = false;
                    }
                }
            }

Open in new window

I have not been able to make it work for me.

Question: Could you please show me how this is done?

I am looking for the required modification to code above and where it should be placed in my code below:
protected void createMonthlyChartImagesSmall(string YYYY, int RegionID, string Region, int Metric_ID, int MedCtrID, string MedCenter, string chartImageName)
    {
        //  protected void createChart1()
        var filePathName = "~\\image\\" + chartImageName + "Small.png";
        if (!File.Exists(Server.MapPath(filePathName)))
        {
            // some dummy values...
            Session["Metric_ID"] = Metric_ID;
            Session["YYYY"] = YYYY;
            Session["MedCtr_ID"] = MedCtrID;

            SqlDataSource mySqlDataSource = new SqlDataSource();
            mySqlDataSource.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ROD_July18ConnectionString"].ConnectionString;
            mySqlDataSource.SelectCommand = "spMonthlyChart";
            mySqlDataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
            mySqlDataSource.SelectParameters.Add(new SessionParameter("Metric_ID", DbType.Int32, "Metric_ID"));
            mySqlDataSource.SelectParameters.Add(new SessionParameter("YYYY", DbType.String, "YYYY"));
            mySqlDataSource.SelectParameters.Add(new SessionParameter("MedCtr_ID", DbType.Int32, "MedCtr_ID"));

            Chart chart = new Chart();

            Series series = new Series("Default");
            series.ChartType = SeriesChartType.Column;
            chart.Series.Add(series);

            Series series2 = new Series("Default2");
            series2.ChartType = SeriesChartType.Line;
            series2.Color = System.Drawing.Color.Purple;// change color to put
            series2.BorderWidth = 1; // this is actually the line width...
            series2.BorderDashStyle = ChartDashStyle.Dot;

            chart.Series.Add(series2);

            ChartArea chartArea = new ChartArea();
            Axis yAxis = new Axis(chartArea, AxisName.Y);
            Axis xAxis = new Axis(chartArea, AxisName.X);

            series.XValueMember = "ColName"; // X
            series.YValueMembers = "ColValue"; // Y1
            series2.XValueMember = "ColName"; // X
            series2.YValueMembers = "Target"; // Y2
            chart.DataSource = mySqlDataSource;
            chart.DataBind();

            series2.IsValueShownAsLabel = false;
            series2.Points[0].IsValueShownAsLabel = true;

            chartArea.BackColor = Color.Transparent;// chart.ChartAreas.col
            chart.BackColor = Color.Transparent;
            chart.Series["Default"].Color = System.Drawing.Color.FromArgb(250, 140, 172, 0);
            chart.Series["Default"].Points[0].Color = System.Drawing.Color.FromArgb(250, 224, 0, 0);
            chart.Series["Default"].Points[chart.Series["Default"].Points.Count - 1].Color = System.Drawing.Color.FromArgb(250, 225, 128, 0);
          //  series.IsValueShownAsLabel = true; // 3 show value

            

            series.LabelForeColor = System.Drawing.Color.Black;
            series.LabelAngle = 90;
            //chart.ChartAreas[0].AxisX.LabelStyle.Angle = 90;
            chartArea.AxisX.MajorGrid.Enabled = false; // 1 don't show grid
            chartArea.AxisY.MajorGrid.Enabled = false;// 1 don't show grid
            chartArea.AxisY.LabelStyle.Enabled = false; // 2 remove y labels
            // 
            chartArea.AxisX.LabelStyle.Font = new Font("Arial", 8);
            chartArea.AxisX.LabelStyle.Angle = 90;
           // chartArea.AxisX.PositionToValue = midButtonsLabel;

            chartArea.AxisX.LabelStyle.ForeColor = System.Drawing.Color.White;
            chartArea.AxisX.LabelAutoFitStyle = 0;//??????? 
            //chart.BorderSkin.SkinStyle = BorderSkinStyle.FrameThin1;// add thin fram to border???????????
            chartArea.AxisY.MajorTickMark.Enabled = false; //5.remove tick marks and add border
            chartArea.BorderDashStyle = ChartDashStyle.Solid; //6. add border
            chartArea.BorderWidth = 1;
            chartArea.BorderColor = System.Drawing.Color.Black; //6. add border

            ////chartArea.AxisX.IsLabelAutoFit = true;
            //// chartArea.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.LabelsAngleStep30;
            chartArea.AxisX.LabelStyle.Enabled = true;
            chartArea.AxisX.LabelStyle.Angle = -90; // 4 rotate x labels
            chartArea.AxisX.Interval = 1;// xhow all labels

            if (Metric_ID == 115 || Metric_ID == 113)
            {
                chart.Series["Default"].Color = System.Drawing.Color.FromArgb(255, 224, 0, 0);//light red;
                chart.Series["Default"].BackGradientStyle = GradientStyle.DiagonalLeft;
                chart.Series["Default"].BackSecondaryColor = System.Drawing.Color.FromArgb(255, 147, 0, 0);//dark red
            }
            else
            {
                chart.Series["Default"].Color = System.Drawing.Color.FromArgb(255, 152, 200, 0);//light green;
                chart.Series["Default"].BackGradientStyle = GradientStyle.DiagonalLeft;
                chart.Series["Default"].BackSecondaryColor = System.Drawing.Color.FromArgb(255, 129, 132, 0);//dark green
            }

            chart.Series["Default"].Points[0].Color = System.Drawing.Color.FromArgb(255, 255, 150, 0);//light orange ;//FromArgb(255, 224, 0, 0);//light Red;
            chart.Series["Default"].Points[0].BackGradientStyle = GradientStyle.DiagonalLeft;
            chart.Series["Default"].Points[0].BackSecondaryColor = System.Drawing.Color.FromArgb(255, 255, 105, 0);//Dark orange;//FromArgb(255, 147, 0, 0);//DarkRed;
            chart.Series["Default"].Points[chart.Series["Default"].Points.Count - 1].Color = System.Drawing.Color.FromArgb(255, 190, 124,207);//light purple;
            chart.Series["Default"].Points[chart.Series["Default"].Points.Count - 1].BackGradientStyle = GradientStyle.DiagonalLeft;
            chart.Series["Default"].Points[chart.Series["Default"].Points.Count - 1].BackSecondaryColor = System.Drawing.Color.FromArgb(255, 153,66,123);//dark purple
            chartArea.BackColor = System.Drawing.Color.White;// SlateGray;

            series.Font = new Font("Arial", 8f);

            chart.Series["Default"]["BarLabelStyle"] = "Center";  // This will change Label Position
            chart.Series["Default"].LabelAngle = 90;    // This will rotate Data Label 
            
            chart.Width = new Unit(214, UnitType.Pixel);
            chart.Height = new Unit(158, UnitType.Pixel);
            chart.ChartAreas.Add(chartArea);

            chart.PostPaint += new EventHandler<ChartPaintEventArgs>(chart_PostPaint);

            string filename = "~\\image\\" + chartImageName + "Small.png";
            chart.SaveImage(Server.MapPath(filename), ChartImageFormat.Png);

        }
    }

Open in new window

0
Mike Eghtebas
Asked:
Mike Eghtebas
1 Solution
 
Robert SchuttSoftware EngineerCommented:
I can't seem to get that code working 'as is'. However, it does work when I change the logic around: set label on series to false and enable showing the point label only if value != 0...
                series.Points[7].YValues[0] = 0; // test
                series.IsValueShownAsLabel = false;

                //hide label value if zero -> now show if not zero
                foreach (Series srs in chart.Series) {
                    if (srs.Name == "Default") {
                        foreach (DataPoint point in srs.Points) {
                            if (point.YValues.Length > 0 && (double)point.YValues.GetValue(0) != 0) {
                                point.IsValueShownAsLabel = true;
                            }
                        }
                    }
                }

Open in new window

Note that this does not combine with the implementation of a PostPaint event handler that I came up with earlier, because that shows the labels for all points without checking anything. You would have to add that check:
        void chart_PostPaint(object sender, ChartPaintEventArgs e) {

            Font fnt = new Font("Arial", 8);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;

            if (e.ChartElement.GetType().Name.Equals("Series")) {
                Series s = (Series)e.ChartElement;
                if (s.Name == "Default") {
                    for (int p = 0; p < s.Points.Count; p++) {
                        if (s.Points[p].IsValueShownAsLabel) {
                            s.Points[p].IsValueShownAsLabel = false; // don't show it in the standard way as well!
                            PointF p1 = new PointF(
                                (float)e.ChartGraphics.GetPositionFromAxis(s.ChartArea, AxisName.X, (e.Chart.ChartAreas[s.ChartArea].AxisX.Maximum - e.Chart.ChartAreas[s.ChartArea].AxisX.Minimum - 1) * (p + 1) / (s.Points.Count)),
                                (float)e.ChartGraphics.GetPositionFromAxis(s.ChartArea, AxisName.Y, s.Points[p].YValues[0] / 2)
                            );
                            PointF p1a = e.ChartGraphics.GetAbsolutePoint(p1);
                            // note the order: first move center to actual position, then rotate, then draw string at (0, 0)
                            e.ChartGraphics.Graphics.TranslateTransform(p1a.X, p1a.Y);
                            e.ChartGraphics.Graphics.RotateTransform(-90);
                            e.ChartGraphics.Graphics.DrawString(s.Points[p].YValues[0].ToString(), fnt, Brushes.Black, 0, 0, sf);
                            e.ChartGraphics.Graphics.ResetTransform();
                        }
                    }
                }
            }
        }

Open in new window

A danger here would be if the chart would get updated, it loses the labels because of the "s.Points[p].IsValueShownAsLabel = false;", which is necessary to suppress the default labels which were disabled before but had to be enabled now to be able to disable only the zeroes.

Another option would of course be to forget about both those pieces of code and just check the value in the PostPaint directly (much simpler but less generic solution):
        void chart_PostPaint(object sender, ChartPaintEventArgs e) {

            Font fnt = new Font("Arial", 8);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;

            if (e.ChartElement.GetType().Name.Equals("Series")) {
                Series s = (Series)e.ChartElement;
                if (s.Name == "Default") {
                    for (int p = 0; p < s.Points.Count; p++) {
                        if (s.Points[p].YValues.Length > 0 && s.Points[p].YValues[0] > 0) {
                            PointF p1 = new PointF(
                                (float)e.ChartGraphics.GetPositionFromAxis(s.ChartArea, AxisName.X, (e.Chart.ChartAreas[s.ChartArea].AxisX.Maximum - e.Chart.ChartAreas[s.ChartArea].AxisX.Minimum - 1) * (p + 1) / (s.Points.Count)),
                                (float)e.ChartGraphics.GetPositionFromAxis(s.ChartArea, AxisName.Y, s.Points[p].YValues[0] / 2)
                            );
                            PointF p1a = e.ChartGraphics.GetAbsolutePoint(p1);
                            // note the order: first move center to actual position, then rotate, then draw string at (0, 0)
                            e.ChartGraphics.Graphics.TranslateTransform(p1a.X, p1a.Y);
                            e.ChartGraphics.Graphics.RotateTransform(-90);
                            e.ChartGraphics.Graphics.DrawString(s.Points[p].YValues[0].ToString(), fnt, Brushes.Black, 0, 0, sf);
                            e.ChartGraphics.Graphics.ResetTransform();
                        }
                    }
                }
            }
        }

Open in new window

[Sorry if this has gotten a bit rambly...]
0
 
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
Thank you Robert.

re> A danger here would be if the chart would get updated, it loses the labels

Because these codes are used just to create static images for later use, the values are not expected to change dynamically. Some chart may be deleted and recreated later on nonetheless.

Mike

I had misunderstood your comment. After reading it again, I was able to understand the point you are making.
0

Featured Post

Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now