?
Solved

column chart data label, position and rotation, c#

Posted on 2014-08-12
4
Medium Priority
?
1,224 Views
Last Modified: 2014-08-17
Please note that this question is not x-axis label, rather it is about data label on the column of the chart.

The following  code does not rotate the data labels on the columns ( see line 59).

Question: How can I change  the code below to do the following:
      Part 1: Rotate the data labels by 90 degrees, and
      Part 2: To position the data label values inside (middle portion) of their respective columns.

Do I need to reduce font-size to be inside the column?

As it stands, the data labels are positioned at the tip of the columns.
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;
            //series2.IsValueShownAsLabel = true;

            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(50, 140, 172, 0);
            chart.Series["Default"].Points[0].Color = System.Drawing.Color.FromArgb(50, 224, 0, 0);
            chart.Series["Default"].Points[chart.Series["Default"].Points.Count - 1].Color = System.Drawing.Color.FromArgb(30, 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;
//            protected void SummaryChart_Customize(object sender, EventArgs e)
//{
//    //hide label value if zero
//    foreach (System.Web.UI.DataVisualization.Charting.Series series in SummaryChart.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;
//            }
//        }
//    }
//}
            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
            //  series.LabelStyle.Font = new Font("Palatino Linotype", 12);

     //       chartArea.BackGradientStyle = GradientStyle.DiagonalLeft;
            chartArea.BackColor = System.Drawing.Color.White;// SlateGray;
     //       chartArea.BackSecondaryColor = System.Drawing.Color.White;
            // chartArea.Position.X = 0;
            //  chartArea.Position.Y = 0;

            series.Font = new Font("Arial", 8f);
            // chartArea.AxisX.Interval = 1;
  //          chart.Titles.Add(string.Format("{0}{1}{2} ", MedCenter, ", Metric " + Metric_ID, " - " + YYYY));
 //           chart.Titles[0].Alignment = ContentAlignment.TopLeft;
 //           chart.Titles[0].Font = new Font("Tahoma", 20f);
  //          chart.Titles[0].ForeColor = System.Drawing.Color.White;
            //chart.Titles[0].Font=Bold;

            chart.Width = new Unit(214, UnitType.Pixel);
            chart.Height = new Unit(158, UnitType.Pixel);
            chart.ChartAreas.Add(chartArea);
            string filename = "C:\\Users\\Mike\\Documents\\_smc\\__CS37\\MasterPageTestJul25\\image\\" + chartImageName + "Small.png";
            chart.SaveImage(filename, ChartImageFormat.Png);

        }
    }

Open in new window

0
Comment
Question by:Mike Eghtebas
  • 3
4 Comments
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40258083
Could it be that this is not possible? I looked into CustomProperties and TextAnnotations but couldn't find a solution.

Here is a solution using the PostPaint event; after creating the chart object (line 20) add this:
chart.PostPaint += new EventHandler<ChartPaintEventArgs>(chart_PostPaint);

Open in new window

Then add this event handler:
        void chart_PostPaint(object sender, ChartPaintEventArgs e) {

            Font fnt = new Font("Arial", 8);
            StringFormat sf = new StringFormat(StringFormatFlags.DirectionVertical);
            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++) {
                        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);
                        e.ChartGraphics.Graphics.DrawString(s.Points[p].YValues[0].ToString(), fnt, Brushes.Black, p1a, sf);
                    }
                }
            }
        }

Open in new window

0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 40258812
Robert,

You are amazing. You make it all possible.

The data points show up rotated (I suppose by 90 degrees) in the middle of the columns. I tried to locate the angle value and change it to -90 (for a better readability) but I didn't see any angle entry.

Question: How can I rotate the values (now reads top-to-bottom) to read Bottpm-to-top?

Thank you,

Mike
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40260191
Hmm good one. The rotation in this case is done by StringFormatFlags.DirectionVertical, but I don't see an obvious way to make it go from bottom to top. I did find some examples to draw a string rotated the other way with some more customization but the result was unreadable so I'm trying another option, will need some time though.
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 2000 total points
ID: 40260200
In the end the solution was pretty simple but initially I had forgotten to take out the StringFormatFlags.DirectionVertical so when you rotate that it's back to normal... here's the code, you may wanna play around with font size and move a pixel or 2 here and there:
        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++) {
                        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

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Screencast - Getting to Know the Pipeline
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question