Scrolling/Moving MS chart area to highlighted datapoint when in zoom state - c#

In windows form, I am displaying data in MS Chart from Datagridview.
When selecting an row in the datagridview, I am highlighting the corresponding datapoint in the chart with different color.
When chart is in zoom state , if a datapoint is highlighted newly and if it is not in the visible state, I have to scroll/move the chart to highlighted datapoint.
chart.ChartAreas.Add("LineGraphHistory");
chart.ChartAreas["LineGraphHistory"].AxisX.Title = "X Axis";
chart.ChartAreas["LineGraphHistory"].AxisX.MajorGrid.LineColor = System.Drawing.Color.Black;
chart.ChartAreas["LineGraphHistory"].AxisX.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
chart.ChartAreas["LineGraphHistory"].AxisY.Title = "Y Axis";
chart.ChartAreas["LineGraphHistory"].AxisY.MajorGrid.LineColor = Color.Black;
chart.ChartAreas["LineGraphHistory"].AxisY.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
chart.ChartAreas["LineGraphHistory"].BackColor = Color.White;
chart.ChartAreas["LineGraphHistory"].CursorX.IsUserEnabled = true;
chart.ChartAreas["LineGraphHistory"].CursorX.IsUserSelectionEnabled = true;
chart.ChartAreas["LineGraphHistory"].CursorX.Interval = 0;
chart.ChartAreas["LineGraphHistory"].AxisX.ScaleView.Zoomable = true;
chart.ChartAreas["LineGraphHistory"].AxisX.ScrollBar.Enabled = true;
chart.Legends.Add("Legend");
chart.Legends["Legend"].BorderColor = Color.Tomato;
chart.DataSource = CSVDataTable;
chart.ChartAreas["LineGraphHistory"].AxisX.IntervalType = DateTimeIntervalType.Seconds;
chart.ChartAreas["LineGraphHistory"].AxisX.LabelStyle.Format ="dd-MM-yyyy\n hh:mm:ss"; ;
chart.Series[s].XValueType =ChartValueType.DateTime ;
chart.DataBind();
chart.Update();
private void cDataGrid_SelectionChanged(object sender, EventArgs e)
{
int nCount = csvDataGrid.SelectedRows.Count;
if (nCount > 0)
{
for (int i = 0; i < nCount; i++)
{
int index = csvDataGrid.SelectedRows[i].Index;
if (index >= csvDataGrid.Rows.Count-1)
return;
for (int k = 0; k < chart.Series.Count; k++)
{
DataPointCollection pr = chart.Series[k].Points;
pr[index].MarkerColor = Color.DarkGoldenrod;
pr[index].MarkerStyle = MarkerStyle.Star10;
pr[index].MarkerSize = 20;
// chart.
}
chart.Update();
}
}
}
How to achieve this?
As Taw suggested I tried to set scaleview position.
I have 10 datapoints. The range of x value of datapoints are 20 to 200. Each x value has equal difference of 20. The view size is 100. In zoom mode, when I scrolling to maximum the x range is 101 to 200 in the view , the last point is displayed as 5th point in the view. Whereas if I use your code to set scaleview position to highlight last datapoint , the x range becomes 180 to 240 and highlighted last datpoint is visible as first range.
Why paintviewmin and paintviewmax values are changing?
The images are

You need to calculate the offset from the DataPoint dp.XValue, maybe like this:
Axis ax = chart.ChartAreas[0].AxisX;
var size = ax.ScaleView.ViewMaximum - ax.ScaleView.ViewMinimum;
ax.ScaleView.Position = dp.XValue - size / 2.0;
Example:
Update: When smaller data sets are displayed the automatically added margins mess up the simple calculation above. To avoid this you can add:
chart.ChartAreas[0].AxisX.IsMarginVisible = false;

Related

Multiple chart areas in one column

I have a chart with multiple chart areas. When I press a button a new chart area is being created etc.
My problem is that after adding some chart areas I get the following result :
I want to have each chart area in only one column, one after the other like this :
is this possible ?
EDIT: Adding chart areas dynamically
on the left it is the chart with 3 chart areas added and the right is the chart with 4 areas.
Use property ChartArea.AlignWithChartArea
Through the use of the AlignWithChartArea, AlignmentOrientation and AlignmentStyle properties, it is possible to align or synchronize two or more chart areas horizontally, vertically or both.
First, set the AlignWithChartArea property to the name of a ChartArea object. This chart area will then be aligned, based on the AlignmentStyle setting, which defines the alignment to use, and the AlignmentOrientation setting, which defines the elements of the chart area that should be used to set the alignment.
So to put ChartArea2 below ChartArea1:
ChartArea2.AlignWithChartArea1;
ChartArea2.AlignmentStyle = AreaAlignmentStyles.Position;
ChartArea2.AlignmentOrientation = AreaAlignmentOrientation.Vertical;
Here is how you can achive what you need, also referring for your question here: https://stackoverflow.com/questions/67124754/dynamically-add-chart-areas-in-vertical-alignment
Use the Position property and please read comments inside the code:
private void button1_Click(object sender, EventArgs e)
{
List<ChartArea> Areas = new List<ChartArea>();
int numberOfAreas = 5;
chart1.Legends[0].Enabled = false;
for (int k = 1; k <= numberOfAreas; k++) // YOU WANT 5 and not 4 AREAS - changed k< to k<=
{
var S1 = new Series();
chart1.Series.Add(S1);
S1.Name = k.ToString();
for (int j = 0; j < 100; j += 10) S1.Points.AddXY(j, j / 10);
S1.Color = Color.Transparent;
Areas.Add(new ChartArea(k.ToString()));
chart1.ChartAreas.Add(Areas[k - 1]); // IT IS k-1 and not k - we start counting from 0
S1.ChartArea = k.ToString();
chart1.ChartAreas[k - 1].AlignWithChartArea = chart1.ChartAreas[k - 1].Name;
chart1.ChartAreas[k - 1].AlignmentStyle = AreaAlignmentStyles.Position;
chart1.ChartAreas[k - 1].AlignmentOrientation = AreaAlignmentOrientations.Vertical;
}
// NOW THE IMPORTANT PART
float currentHeight = 0;
foreach (var itm in Areas)
{
itm.Position.Height = 100 / numberOfAreas; // Note: the valus are in percenteges and not absolute pixels
itm.Position.Y = currentHeight;
itm.Position.X = 5;
itm.Position.Width = 95;
currentHeight += 100 / numberOfAreas;
}
}
OUTPUT:

Visual bug when inputting numbers too high into a Windows Form app line graph

I am using C# to try to input numbers into a line graph from a text file. The numbers in the text file are big, as in -30000. Every time I input a large number into the graph, I get a visual glitch that turns the graph black. Am I doing something wrong or is it a bug?
void ChartLoad()
{
var chart = LineGraph.ChartAreas[0];
chart.AxisX.IntervalType =
System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Number;
chart.AxisX.LabelStyle.Format = "";
chart.AxisY.LabelStyle.Format = "";
chart.AxisX.LabelStyle.IsEndLabelVisible = true;
chart.AxisX.Interval = 0.5;
chart.AxisY.Interval = 10;
LineGraph.Series[0].IsVisibleInLegend = false;
LineGraph.Series.Add("Line1");
LineGraph.Series["Line1"].ChartType =
System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
LineGraph.Series["Line1"].Color = Color.Green;
LineGraph.Series.Add("Line2");
LineGraph.Series["Line2"].ChartType =
System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
LineGraph.Series["Line2"].Color = Color.Blue;
LineGraph.Series["Line1"].Points.AddXY(30000, 30000);
LineGraph.Series["Line1"].Points.AddXY(-30000, -30000);
}
The problem is the grid. You have an amazingly small intervall compared to the range of your values. The grid is so tight that it webbes a narrow carpet of gridlines onto your chart.
You could solve it by
switching of the grid:
chart.AxisX.MinorGrid.Enabled = false;
chart.AxisX.MajorGrid.Enabled = false;
chart.AxisY.MajorGrid.Enabled = false;
chart.AxisY.MinorGrid.Enabled = false;
Or by adjusting the axes intervalls to a reasonable number depending on the range of your values. You will see immidiately a difference when you set the interval to:
chart.AxisX.Interval = 10000;
chart.AxisY.Interval = 10000;
Here is a method that could do this for you:
private void AddValuesAndAdjustInterval(string series, double xValue, double yValue)
{
LineGraph.Series[series].Points.AddXY(xValue, yValue);
var chart = LineGraph.ChartAreas[0];
double maxValueX = LineGraph.Series[series].Points.Select(x=> x.XValue).Max();
double minValueX = LineGraph.Series[series].Points.Select(x=> x.XValue).Min();
double maxValueY = LineGraph.Series[series].Points.SelectMany(x=> x.YValues).Max();
double minValueY = LineGraph.Series[series].Points.SelectMany(x => x.YValues).Min();
int stepSize = 20; // the smaller this value the larger the grid separation
chart.AxisX.Interval = (maxValueX - minValueX) / stepSize;
chart.AxisY.Interval = (maxValueY - minValueY) / stepSize;
}
Now you can use it to add values:
AddValuesAndAdjustInterval("Line1", 30000, 30000);
AddValuesAndAdjustInterval("Line1", -30000, -30000);

MS Charts showing wrong X Axis values

I have one chart control with two buttons.First call candlestick chart.Second call bar chart.If I call only one of them everything is fine.But if I click the button for bar chart it gets the X Axis values from the candlestick chart.Bar chart X Axis should be from 0-15.
How they look:
https://imgur.com/a/IICYh
On formload candlestick chart is loaded first.Everything is still fine.
When Close/Open button for the bar chart is clicked.Its left with the X Axis values from candlestick chart.
When I click Chart button for the candlestick chart after hitting Close/Open.
Y Axis values are missing now.
Methods for calling the charts:
public void CandleStickChartMain()
{
// clear the chart
if (ChartCandle.Series.Count > 0) this.ChartCandle.Series[0].Points.Clear();
this.ChartCandle.Series.Clear();
this.ChartCandle.Titles.Clear();
//Clear Grid
ChartCandle.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 0;
ChartCandle.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 0;
//Series
ChartCandle.Series.Add("Date");
ChartCandle.Series["Date"].YValuesPerPoint = 4;
ChartCandle.Series["Date"].XValueMember = "Day";
ChartCandle.Series["Date"].YValueMembers = "High,Low,Open,Close";
ChartCandle.Series["Date"].XValueType = ChartValueType.DateTime;
ChartCandle.Series["Date"].CustomProperties = "PriceDownColor=Red,PriceUpColor=Green";
ChartCandle.Series["Date"]["OpenCloseStyle"] = "Triangle";
ChartCandle.Series["Date"]["ShowOpenClose"] = "Both";
ChartCandle.DataManipulator.IsStartFromFirst = true;
ChartCandle.Series["Date"].ChartType = SeriesChartType.Candlestick;
//Axis Y Minimum
ChartCandle.ChartAreas["ChartArea1"].AxisY.Minimum = Open.Min() - (Open.Min() / 50);
//Data Binding
ChartCandle.DataSource = ChartDataTable;
ChartCandle.DataBind();
}
public void BarChart()
{
// clear the chart
if (ChartCandle.Series.Count > 0) this.ChartCandle.Series[0].Points.Clear();
this.ChartCandle.Series.Clear();
this.ChartCandle.Titles.Clear();
// Set palette
this.ChartCandle.Palette = ChartColorPalette.Excel;
// Set title
this.ChartCandle.Titles.Add("Price Data Open/Close");
//Add series
//Series Open
var seriesOpen = ChartCandle.Series.Add("Open");
for (int i = 0; i < Open.Length; i++)
{
seriesOpen.Points.Add(Open[i]);
}
//Series Close
var SeriesClose = ChartCandle.Series.Add("Close");
for (int i = 0; i < Close.Length; i++)
{
SeriesClose.Points.Add(Close[i]);
}
var chartAreaOpenClose = ChartCandle.ChartAreas[seriesOpen.ChartArea];
// Zoom and scroll options
// set view range to [0,max]
chartAreaOpenClose.AxisX.Minimum = 0;
chartAreaOpenClose.AxisX.Maximum = Open.Length + 1;
// enable autoscroll
chartAreaOpenClose.CursorX.AutoScroll = true;
// let's zoom to [0,blockSize] (e.g. [0,100])
chartAreaOpenClose.AxisX.ScaleView.Zoomable = true;
chartAreaOpenClose.AxisX.ScaleView.SizeType = DateTimeIntervalType.Number;
int position = 0;
int size = 15;
chartAreaOpenClose.AxisX.ScaleView.Zoom(position, size);
// disable zoom-reset button (only scrollbar's arrows are available)
chartAreaOpenClose.AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
// set scrollbar small change to blockSize (e.g. 100)
chartAreaOpenClose.AxisX.ScaleView.SmallScrollSize = 15;
// additional
ChartCandle.ChartAreas[0].AxisY.IsStartedFromZero = false;
}

MS chart candlestick How to set tail colors

I am currently developing a candlestick chart with mschart in visual C#.
I have now created two charts and created the charts as follows
Question 1. View the Candlestick Chart at the top. I would like to apply the tail color of each rod as red or blue.
Question 2. View the bar chart at the bottom. I would like to apply Red or Blue color to this chart. I want to apply the same color to the top of the Candlestick chart. How can I do it ?
[source]
DataTable table_ChartData = new DataTable();
table_ChartData.Columns.Add("Id");
table_ChartData.Columns.Add("Open");
table_ChartData.Columns.Add("Close");
table_ChartData.Columns.Add("High");
table_ChartData.Columns.Add("Low");
table_ChartData.Columns.Add("Day");
dataGridView1.DataSource = table_ChartData;
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = max;
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = min;
chart1.ChartAreas["ChartArea1"].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.WordWrap;
chart1.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = true;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = true;
chart1.Series["Candle"].XValueMember = "Day";
chart1.Series["Candle"].YValueMembers = "High,Low,Open,Close,Volume";
chart1.Series["Candle"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
chart1.Series["Candle"].CustomProperties = "PriceDownColor=Blue,PriceUpColor=Red";
chart1.Series["Candle"]["OpenCloseStyle"] = "Triangle";
chart1.Series["Candle"]["ShowOpenClose"] = "Both";
chart1.DataSource = table_ChartData;
chart1.DataBind();
////////////////////////////////////////////////////////////
chart2.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 1;
chart2.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 1;
chart2.ChartAreas["ChartArea1"].AxisY.Maximum = v_max + (v_max / 10);
chart2.ChartAreas["ChartArea1"].AxisY.Minimum = v_min / 2;
chart2.ChartAreas["ChartArea1"].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.WordWrap;
chart2.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = true;
chart2.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = true;
chart2.Series["Bar"].XValueMember = "Day";
chart2.Series["Bar"].YValueMembers = "Volume";
chart2.Series["Bar"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
chart2.Series["Bar"].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
chart2.DataSource = table_ChartData;
chart2.DataBind();
In a Candlestick Chart there are CustomProperties to automatiaclly set the colors of the boxes, depending on the trend:
someSeries.SetCustomProperty("PriceUpColor", "Green");
someSeries.SetCustomProperty("PriceDownColor", "Red");
Unfortunately there is no way to set the colors of the lines that connect the high- and low-values.
But, unless you have messed with other Custom attributes and if the x-values are meaningful, you can easily draw those lines, and by drawing the top and the bottom part separately you can also use different colors.
Here is an example:
private void chart6_PostPaint(object sender, ChartPaintEventArgs e)
{
ChartArea ca = chart6.ChartAreas[0];
Series s = chart6.Series[0];
Pen hiPen = Pens.Green;
Pen loPen = Pens.Red;
if (e.ChartElement == s)
foreach (DataPoint dp in s.Points)
{
float x = (float)ca.AxisX.ValueToPixelPosition(dp.XValue);
float y_hi = (float)ca.AxisY.ValueToPixelPosition(dp.YValues[0]);
float y_low = (float)ca.AxisY.ValueToPixelPosition(dp.YValues[1]);
float y_open = (float)ca.AxisY.ValueToPixelPosition(dp.YValues[2]);
float y_close = (float)ca.AxisY.ValueToPixelPosition(dp.YValues[3]);
e.ChartGraphics.Graphics.DrawLine(hiPen, x, y_low, x, Math.Min(y_close, y_open));
e.ChartGraphics.Graphics.DrawLine(loPen, x, y_hi, x, Math.Max(y_close, y_open));
}
}
To set Colors for the 2nd Chart's points you need to loop over the points as there Colors cannot be set in binding.
The code is simple:
void SetColors(Series candles, Series columns)
{
for (int i = 0; i < candles.Points.Count; i++)
{
DataPoint dp = candles.Points[i];
columns.Points[i].Color =
dp.YValues[2] > dp.YValues[3] ? Color.Red : Color.Green;
}
}
Call it after binding!
Result:
Note that to avoid seeing the original lines shine through we set the BorderWidth to 0:
someSeries.BorderWidth = 0;
Simple way:
priceSerie.Points[index].Color = Color.Blue;
// priceSerie.Points[index].BorderColor = Color.Magenta;

ASP.NET (C#) Graph

I am wondering how can I remove the 3 horizontal red lines on the stock graph as shown in image bellow. Please ignore the dots/squares on the image they are irrelevant. I think I have searched every google page there is and went through every option asp.net has... and could not figure out it. Any help is greatly appreciated!
Code that generated this graph:
Double[] test = new Double[] { 10, 50 };
Chart1.Series[0].ChartType = SeriesChartType.Stock;
Chart1.Series[0].YAxisType = AxisType.Primary;
Chart1.Series[0].Color = Color.Red;
Chart1.Series[0].BorderWidth = 10;
Chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
Chart1.Series[0]["PixelPointWidth"] = "5";
Chart1.Series.Add(new Series("Test Series"));
Chart1.Series[1].ChartType = SeriesChartType.Point;
Chart1.Series[1].YAxisType = AxisType.Primary;
Chart1.Series[1].Color = Color.Black;
Chart1.Series[1].BorderWidth = 3;
Chart1.Series[1].MarkerSize = 15;
Chart1.Series.Add(new Series("New Series"));
Chart1.Series[2].ChartType = SeriesChartType.Point;
Chart1.Series[2].YAxisType = AxisType.Primary;
Chart1.Series[2].Color = Color.Orange;
Chart1.Series[2].BorderWidth = 3;
Chart1.Series[2].MarkerSize = 15;
Chart1.Series[0].Points.Add(new Double[] {-10, 50});
Chart1.Series[1].Points.Add(25);
Chart1.Series[2].Points.Add(20);
for (int i = 0; i < 2; i++)
{
Chart1.Series[0].Points.Add(test);
Chart1.Series[1].Points.Add(25);
Chart1.Series[2].Points.Add(20);
}
Okay, after looking into it obsessively, I think that I have a solution. Just adding the two Y values, the chart has a default value of zero for a marker (high or low?). By specifying that you will add the four values (open, close, high, low - not certain about the high/low order), you can hide those lines by making them fall within your open/close range, and by setting the PixelPointWidth to equal or less then your BorderWidth.
// IMPORTANT: add the ", 4" to indicate that you have the four Y values
Chart1.Series.Add(new Series("Stock", 4));
Chart1.Series["Stock"].ChartType = SeriesChartType.Stock;
Chart1.Series["Stock"].YAxisType = AxisType.Primary;
Chart1.Series["Stock"].Color = Color.Red;
Chart1.Series["Stock"].BorderWidth = 10;
Chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
// Set <= BorderWidth, so that it's effectively hidden
Chart1.Series["Stock"]["PixelPointWidth"] = "10";
Chart1.Series["Stock"].Points.AddY(10, 50, 20, 30); // open, close, high, low.
That was a little hard to track down. Whew.

Categories