MSDN charts changing point values realtime? - c#

I want to use MSDN charts to represent realtime data i'm getting from a telnet application. For testing purpose i have added a button to alter the chart manually. I manually made the chart and it has 0 to 5 points on the X axis with values different values on the X. The series is named by it's default "Series1".
I tried the following:
chart1.Series["Series1"].Points.ElementAt(0).SetValueY(40); //Nothing happens
chart1.Series["Series1"].Points.ElementAt(1).SetValueXY(1, 20); //Nothing happens
chart1.Series["Series1"].Points[0].SetValueY(40); //Nothing happens
chart1.Series["Series1"].Points.ElementAt(1).YValues.SetValue(10, 0); //Nothing happens
chart1.Series["Series1"].Points.Clear(); //Removes all points like it should.
So how do i change datapoint entries on runtime?
-EDIT-
If i modify a point using chart1.Series["Series1"].Points.ElementAt(0).SetValueY(40); and add a point after this with chart1.Series["Series1"].Points.AddXY(1, 40); the modified point does snap into it's modified place. The conclusion is that modifying does change the points Y value but the graph does not get refreshed. The function AddXY() seems to autorefresh. I cannot seem to find a way to call Refresh() manually.

Call chart1.Refresh() after changing the value; it will force a redraw of the chart, picking up the new values.

I've just found out that SetValueY() does not update the maximum interval in the Y axis. Therefore, if your current maximum is 0, it will not show anything higher than 0.

I do this:
public static void Refresh(this Chart chart) // update changed data
{
chart.Series[0].Points.AddXY(1, 1);
chart.Update();
chart.Series[0].Points.RemoveAt(chart.Series[0].Points.Count-1);
}
chart1.Refresh();

DataTable dtChartDataSource = Input from your side.
foreach (DataColumn dc in dtChartDataSource.Columns)
{
//a series to the chart
if (chart.Series.FindByName(dc.ColumnName) == null)
{
series = dc.ColumnName;
chart.Series.Add(series);
chart.Series[series].ChartType = SeriesChartType.Column;
foreach (DataRow dr in dtChartDataSource.Rows)
{
double dataPoint = 0;
double.TryParse(dr[dc.ColumnName].ToString(), out dataPoint);
Yourchart.Series[seriesName].Points.AddXY("customStringsOnAxis", dataPoints);
}
}
}
It will add the x axis data and Y axis values to the Column chart.
Hope its helps

Related

C# Chart control : X value of a horizontal bar chart is 0 for all points in the serie

I have a horizontally stacked bar chart in my app, and I'm trying to figure out how to get the X axis value when the user clicks on a bar. The problem is when I look at the values at runtime, the Y values are fine but the X values are all 0.
Screen capture
In the image above, light blue bars are from Series[0] and represent the MTD sales and the darker ones from Series[1] represent last year's sales for the same month. My goal is that when the user double-clicks on a bar, he is taken to the detailed sales report for that salesperson.
I haven't tried switching my chart to a regular bar chart because this is what I will need to look like in the end. But I'm starting to wonder if the reason I'm getting all 0's in the XValue field is because of this or because I am using strings as the type of value.
Has anyone ever encountered this or have any clues as to how to fix it?
Screen capture of points at runtime
You use one of the Bar chart types.
They have their x-axis and y-axis switched compared to most normal types.
Therefore in order to get the values along the horizontal axis you actually want to grab the y-values.
To get at the y-value of the double-clicked datapoint you can do a HitTest like in this code:
private void chart1_MouseDoubleClick(object sender, MouseEventArgs e)
{
var hit = chart1.HitTest(e.X, e.Y, ChartElementType.DataPoint);
if (hit.PointIndex >= 0)
{
DataPoint dp = hit.Series.Points[hit.PointIndex];
Console.WriteLine(dp.YValues[0]);
}
}
Note however that in a stacked bar the values look stacked but each point will still only have its own value.
If you wanted to get at the stacked/summed up values you would have to add up all points below and including the one that was hit. 'Below' here means points at the same x-slot but in lower series!
You will not be able to use the x-values if you have added them as strings since in that case they will all be 0, as you can see in your screenshot.
But since all stacked points in your case will have the same e.PointIndex we can use this to access all points in the series below..:
..
int si = 0;
double vsum = 0;
Series s = null;
do
{
s = chart4.Series[si++];
vsum += s.Points[hit.PointIndex].YValues[0];
} while (hit.Series != s);
Console.WriteLine(vsum);
If you actually want to access the x-values you have two options:
You can explicitly add the strings to the AxisLabel of each DataPoint. While the x-values will still be all 0 the AxisLabels now can be accessed.
Or you can add them as numbers, maybe using some scheme to map the strings to numbers and back and, again set the AxisLabels.
OK so I finally managed to put custom labels on the chart using the Chart.Customize event.
Here is the data I am using for this chart:
Vendeur | Total | idDepartement | idEmploye | TotalLastYear
Ghislain 5256.30 1 56 0.00
Kim 12568.42 1 1 74719.18
Philippe 17565.27 1 44 38454.85
I changed X axis XValueType to Double, and the XValueMember to idEmploye.
Result
As you can see, it's not very user friendly to have employee id's on a chart. This is where the Customize event gets useful.
Here is my event:
private void chart1_Customize(object sender, EventArgs e)
{
// Set X axis interval to 1, label will be centered (between 0.5 and 1.5)
chart1.ChartAreas[0].AxisX.Interval = 1;
double startOffset = 0.5;
double endOffset = 1.5;
chart1.ChartAreas[0].AxisX.CustomLabels.Clear();
// Cycle through chart Datapoints in first serie
foreach (System.Windows.Forms.DataVisualization.Charting.DataPoint pt in chart1.Series[0].Points)
{
// First get the dataset used for the chart (from its bindingsource)
DataSet dsSales = (DataSet)bsViewVentesParUtilisateurSignsMoisCourant.DataSource;
// Second get the datatable from that dataset based on the datamember
// property of the bindingsource
DataTable dtSales = (DataTable)dsSales.Tables[bsViewVentesParUtilisateurSignsMoisCourant.DataMember];
// Get a dataview and filter its result based on the current point's XValue
DataView dv = new DataView(dtSales);
dv.RowFilter = "idEmploye=" + pt.XValue.ToString();
// Get the "Salesperson" (or "Vendeur") column value from the first result
// (other rows will have the same value but row 0 is safe)
string firstname = dv.ToTable().Rows[0].Field<string>("Vendeur").ToString();
// Create new customlabel and add it to the X axis
CustomLabel salespersonLabel = new CustomLabel(startOffset, endOffset, firstname, 0, LabelMarkStyle.None);
chart1.ChartAreas[0].AxisX.CustomLabels.Add(salespersonLabel);
startOffset += 1;
endOffset += 1;
}
}
Final result
I am very happy with the result. And now when I double-click on a bar in the chart, I can get the employee id from the X value and generate the code to get the detailed sales report for that person for the given month.

Incorrect empty datapoints display in a fastline chart

I have a fast-line chart series where on X I have DateTime and on Y double values - series is added to the chart with such method:
public virtual bool AddOrUpdateSeries(int caIndex, Series newSeries, bool visibleInLegend)
{
var chartArea = GetChartArea(caIndex);
if (chartArea == null) return false;
var existingSeries = _chart.Series.FirstOrDefault(s => s.Name == newSeries.Name);
if (existingSeries != null)
{
existingSeries.Points.Clear();
AddPoints(newSeries.Points, existingSeries);
}
else
{
newSeries.ChartArea = chartArea.Name;
newSeries.Legend = chartArea.Name;
newSeries.IsVisibleInLegend = visibleInLegend;
newSeries.BorderWidth = 2;
newSeries.EmptyPointStyle = new DataPointCustomProperties { Color = Color.Red };
_chart.Series.Add(newSeries);
}
return true;
}
As you can see, I am setting the style for empty point to be shown in red.
The first points that are added to the series are as follows:
So as you can see, first two points have the same Y value, but in addition -
first one has IsEmpty flag set.
Empty point is added to the series with such piece of code:
series.Points.Add(new DataPoint
{
XValue = _beginOADate,
YValues = new[] { firstDbPoint.Y },
IsEmpty = true
});
where _beginOADate is double OADate value = 42563 = 12/07/2016 00:00 as DateTime.
The second point's DateTime is 15/08/2016 22:20
When chart is displayed with the beginning of the X axis, everything looks ok as on the picture below - empty datapoint starts at 12/07/2016 and lasts until 15/08/2016.
But, when I scroll one position on X, the empty datapoint's red line is not being displayed - instead, whole visible part of empty datapoint's line is displayed as it is non-empty:
Anybody knows how to fix this behaviour so that the whole line starting from Empty datapoint until first non-empty datapoint would always be shown in red?
Of course the dummy solution would be to add one more extra empty datapoint very close to the first non-empty point, but I don't like that solution.
The ChartType.FastLine is much faster the the simple Line chart but to be so fast it makes several simplifications in rendering, which means that not all chart features are supported:
The FastLine chart type is a variation of the Line chart that
significantly reduces the drawing time of a series that contains a
very large number of data points. Use this chart in situations where
very large data sets are used and rendering speed is critical.
Some charting features are omitted from the FastLine chart to improve
performance. The features omitted include control of point level
visual attributes, markers, data point labels, and shadows.
Unfortunately EmptyPointStyle is such a 'point level visual attribute'.
So you will need to decide which is more important: The raw speed or the direct and plausible treatment of empty DataPoints.
(I have a hunch that you'll go for your 'dummy solution', which imo is a 1st class workaround ;-)

How to get chart data points value with equal or less than to highlight those data

I'm looking to change my chart series data points if there is an error values. I want to set rule to highlight those data points like below. Please help to get below code working.
// Find first point with a Y2 value of equal or less than 10.
var dataPoint = Chart1.Series[1].Points.Where(x => x.YValues <= 10);
foreach (DataPoint dt in dataPoint)
{
dt.BorderDashStyle = ChartDashStyle.Dot;
dt.Color = Color.Red;
}
DataPoint.YValues is an array.
The YValues property is used to set the Y-values of data points.
Only one Y-value per point is required for all chart types except
bubble, candlestick and stock charts. These chart types require more
than one Y-value because one data point consists of multiple values.
For example, to plot one stock chart column, four values are required:
high, low, open and close values.
The YValues property returns an array of double values when used to
retrieve the Y-values.
Important The YValuesPerPoint property determines the maximum number
of Y-values that all data points in a Series can have. If you specify
more than the allowable number of Y-values, an exception will be
raised.
Unless you are using one of the above special ChartTypes you always will want to use the first element. So simply write:
var dataPoint = Chart1.Series[1].Points.Where(x => x.YValues[0] <= 10);
If you do use one of the three multiple Y-Values chart types you could, depending on the situation for example write this:
var dataPoint = Chart1.Series[1].Points.Where(x => x.YValues.Max() <= 10);
or this:
var dataPoint = Chart1.Series[1].Points.Where(x => x.YValues.Min() <= 10);

draw line chart from maximum point y axis

I have a line chart in my form that get its data by the code comes in the following
foreach (var series in chart2.Series)
{
series.Points.Clear();
}
Series series2 = chart2.Series[0];
SqlCommand cmdchartline = new SqlCommand(myquery, Con);
SqlDataReader reader2 = cmdchartline.ExecuteReader();
while (reader2.Read())
{
chart2.Series[0].Points.AddXY(reader2["myx"].ToString(), reader2["myy"]);
}
I need to connect (0,5000) as a first point to the chart below I mean chart start from (0,5000) on Y axis
You are adding the x-values as strings.
This is usually (*) wrong as they all are 0 now.
Note: The labels still show the strings but otherwise they are useless.
Change this
chart2.Series[0].Points.AddXY(reader2["myx"].ToString(), reader2["myy"]);
to this:
chart2.Series[0].Points.AddXY(reader2["myx"], reader2["myy"]);
If the fields 'myx' and 'myy' are numbers or dates you now can find the maximum for the DataPoint values:
double maxX = chart2.Series[0].Points.Max(x => x.XValues);
double maxY = chart2.Series[0].Points.Max(x => x.YValues[0]);
Now you can add (or insert) the extra DataPoint; you need to decide on its x-value though!
As I wrote the finding the Y-value is simple but the x-values may be less simple. If you don't need the x-values you can keep them as string or, better, you can make the Series 'Indexed'..:
chart2.Series[0].IsXValueIndexed = true;
Then you can insert the extra point to the beginning like this:
chart2.Series[0].Points.InsertXY(0, 0, maxY);
Note that when keeping the x-values as strings you can't:
use a formatting string for the axis or datapoint labels
use a zoom range based on the values (Axis.ScaleView)
use a display range (Axis.Minimum/Maximum)
do any calulations with the x-values
And you can't hope the chart would display the values in a nice proportional manner; instead they will have sit at the same intervals.
(*) Sometimes none of this is needed, like when the x-values are names or persons or cities etc..

MSChart axis CustomLabel angle at RowIndex > 0

Using VisualStudio WindowsForms Form. Creating Chart control in designer.
I'm trying to add some customLabels on charts Axis along WITH the default labels.
To do so I add customLabels with RowIndex property =1. Thus I see default labels AND my customLabels.
Now the problem is that while the default labels are rotated correctly my custom labels are not.
The Axis property LabelStyle.Angle affects only labels that are in RowIndex = 0, i.e. default labels.
And if I put customLabels at RowIndex=0 - all default labels will disappear.
What I see:
What I want to see:
I see no way to do that, really. The reason is probably that the developers decided there simply cannot be enough space for horizontal labels, once you start putting them in one or more extra rows..
Here is a workaround: Make those CustomLabels all transparent and draw them as you like in a xxxPaint event.
Here is an example:
I prepared the CustomLabels :
CustomLabel cl = new CustomLabel();
cl.ForeColor = Color.Transparent;
cl.RowIndex = 1;
...
And I code the drawing like this:
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
Axis ay = chart1.ChartAreas[0].AxisY;
foreach (var cl in ay.CustomLabels)
{
if (cl.RowIndex == 1)
{
double vy = (cl.ToPosition + cl.FromPosition) / 2d;
int y = (int)ay.ValueToPixelPosition(vy);
e.ChartGraphics.Graphics.DrawString(cl.Text,
cl.Axis.TitleFont, Brushes.DarkRed, 0, y);
}
}
}
Do use a Font and Brush of your own liking. Here is the result:
Note that you may need to create more space to the left by tweaking the ChartArea.Position or the ChartArea.InnerPlotPosition, both of which are in 100% and, as usual, default to 'auto'.
For even more rows you need to change the check to cl.RowIndex < 0 and find a nice x position value for the DrawString.

Categories