How to set values in x axis MSChart using C# - c#

I have these XY values:
Series S1 = new Series()
S1.Points.AddXY(9, 25);
S1.Points.AddXY(10, 35);
S1.Points.AddXY(11, 15);
chart1.Series.Add(S1);
but I need to show the X values in the graph like this:
X="9-10"
X="10-11"
X="11-12"
How can I achieve that?
So far this is what I've found:
and here is the code:
private void Form1_Shown(object sender, EventArgs e)
{
chart1.ChartAreas[0].AxisX.Minimum = 7;
chart1.ChartAreas[0].AxisX.Maximum = 15;
Series S1 = new Series();
S1.Points.AddXY(9, 25);
S1.Points.AddXY(10, 35);
S1.Points.AddXY(11, 15);
chart1.Series.Add(S1);
chart1.Series[0].Points[0].AxisLabel = "9-10";
chart1.Series[0].Points[1].AxisLabel = "10-11";
chart1.Series[0].Points[2].AxisLabel = "11-12";
as you can see I work with numbers, and set texts for the X axis labels, but I can do that just for the DataPoints values, I need it for the whole range of values.
Any ideas please?

Here is the answer thanks to sipla:
working with Custom labels and the Customize event:
string[] range = new string[10];
private void Form1_Shown(object sender, EventArgs e)
{
chart1.ChartAreas[0].AxisX.Minimum = 7;
chart1.ChartAreas[0].AxisX.Maximum = 16;
range[0] = "";
range[1] = "7-8";
range[2] = "8-9";
range[3] = "9-10";
range[4] = "10-11";
range[5] = "11-12";
range[6] = "12-1";
range[7] = "1-2";
range[8] = "2-3";
range[9] = "";
Series S1 = new Series();
S1.Points.AddXY(9, 25);
S1.Points.AddXY(10, 35);
S1.Points.AddXY(11, 15);
chart1.Series.Add(S1);
}
int count;
private void chart1_Customize(object sender, EventArgs e)
{
count = 0;
foreach (CustomLabel lbl in chart1.ChartAreas[0].AxisX.CustomLabels)
{
lbl.Text = range[count];
count++;
}
}

Curious as to why your range array was sprawled out like that. It would have been cleaner to put your array in brackets as it was defined and also initialized. e.g.
string[] range = new string[10] {"","7-8","8-9","9-10","10-11","11-12","12-1","1-2","2-3",""};
/*
The tenth element is also likely unnecessary
as it simply repeats the first
element of the array
*/

Related

C# fix chart size

I'm creating an application which plots data from a serial port. My problem is that sometimes chart size increases when values go below the X axis and, as a result, some values on X axis disappear.
I've set min and max Y axis value, so I wonder how it is possible for the horizontal axis to moves gently downward for a while and then disappear - possibly due to a lack of space?.
It occurs only for first and last label, and sometimes the last grid line disappears too.
Here is piece of code which generate chart values:
int minStress = -200, maxStress=200;
double maxTime=20.0, minTime=0.0;
private void timer1_Tick(object sender, EventArgs e)
{
Stress = serialPort1.ReadLine();
label6.Text = Stress;
StressChart.ChartAreas[0].AxisX.Minimum = minTime;
StressChart.ChartAreas[0].AxisX.Maximum = maxTime;
StressChart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
StressChart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
this.StressChart.Series[0].Points.AddXY((minTime + maxTime) / 2, Stress);
minTime=minTime + TimerInt_2/1000;
maxTime=maxTime + TimerInt_2/1000;
serialPort1.DiscardInBuffer();
}
private void cmbTimerInt_SelectedIndexChanged(object sender, EventArgs e)
{
TimerInt = int.Parse(cmbTimerInt.Text);
TimerInt_2=double.Parse(cmbTimerInt.Text);
timer1.Interval = TimerInt;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
minStress = int.Parse(textBox1.Text);
}
catch { }
if (minStress < maxStress)
{
StressChart.ChartAreas[0].AxisY.Minimum = minStress;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
try
{
maxStress = int.Parse(textBox2.Text);
}
catch { }
if (maxStress > minStress)
{
StressChart.ChartAreas[0].AxisY.Maximum = maxStress;
}
}
Here is code which sets chart properties:
chartArea1.AxisX.LabelStyle.Format = "0.0";
chartArea1.Name = "ChartArea1";
this.StressChart.ChartAreas.Add(chartArea1);
legend1.Name = "Legend1";
this.StressChart.Legends.Add(legend1);
this.StressChart.Location = new System.Drawing.Point(225, 12);
this.StressChart.Name = "StressChart";
series1.ChartArea = "ChartArea1";
series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
series1.Legend = "Legend1";
series1.Name = "Series1";
this.StressChart.Series.Add(series1);
this.StressChart.Size = new System.Drawing.Size(1175, 426);
this.StressChart.TabIndex = 5;
this.StressChart.Text = "chart1";
chartArea1.AxisX.LabelAutoFitStyle = 0;
chartArea1.AxisY.LabelAutoFitStyle = 0;
chartArea1.AxisX.MajorTickMark.Size = 0;
chartArea1.AxisX.IsMarginVisible = true;
chartArea1.AxisY.IsMarginVisible = true;
The reason of such behaviour was decimal places number of X axis labels. Solution is to round these values down to one decimal place.
minTime = Math.Round(minTime,1) + Math.Round(TimerInt_2/1000,1);
maxTime = Math.Round(maxTime,1) + Math.Round(TimerInt_2/1000,1);

MS Chart - updating X axis tick values at run time in line chart

My requirement is in my line graph( which is developed with c# MS Chart), I
always need to display 10 points(samples) at a time. The xaxis has interval value 1.
Initially the Xaxis tick values are (1,2,3,4,5,6,7,8,9,10), After 1 second of time interval, I
have to plot 10 points(samples) starts from 2nd point(i.e. I have to skip 1st
point).Now I need to update the xaxis tick values also , it should be starts from
2,now the xaxis tick values should be like 2,3,4,5,6,7,8,9,10,11). Likewise
After every second the starting value of x axis
tick needs to be increased by 1.
How to update Xaxis tick value in the chart dynamically ?
I am using below code
private void Form1_Load(object sender, EventArgs e)
{
loadCsvFile("C:\\mydata.csv");
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.timer1 = new System.Windows.Forms.Timer(this.components);
chart = new System.Windows.Forms.DataVisualization.Charting.Chart();
chart.Location = new System.Drawing.Point(1, 1);
chart.Size = new System.Drawing.Size(700, 700);
// Add a chartarea called "draw", add axes to it and color the area black
chart.ChartAreas.Add("draw");
numofSamples = 10;
chart.ChartAreas["draw"].AxisX.Minimum = 1;
chart.ChartAreas["draw"].AxisX.Maximum = 10;
chart.ChartAreas["draw"].AxisX.Interval = 1;
chart.ChartAreas["draw"].AxisX.Title = "X Axis";
chart.ChartAreas["draw"].AxisX.MajorGrid.LineColor = System.Drawing.Color.Black;
chart.ChartAreas["draw"].AxisX.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
chart.ChartAreas["draw"].AxisY.Minimum = 0;
chart.ChartAreas["draw"].AxisY.Maximum = 1000;
chart.ChartAreas["draw"].AxisY.Interval = 250;
chart.ChartAreas["draw"].AxisY.Title = "Y Axis";
chart.ChartAreas["draw"].AxisY.MajorGrid.LineColor = Color.Black;
chart.ChartAreas["draw"].AxisY.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
chart.ChartAreas["draw"].BackColor = Color.White;
// Create a new function series
chart.Series.Add("Tags");
// Set the type to line
chart.Series["Tags"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
// Color the line of the graph light green and give it a thickness of 3
chart.Series["Tags"].Color = Color.LightGreen;
chart.Series["Tags"].BorderWidth = 3;
chart.Series["Tags"].MarkerStyle = MarkerStyle.Circle;
chart.Series["Tags"].MarkerSize = 10;
chart.Legends.Add("MyLegend");
chart.Legends["MyLegend"].BorderColor = Color.Tomato; // I like tomato juice!
Controls.Add(this.chart);
// hook up timer event
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
timer1.Start();
}
public void loadCsvFile(string filePath)
{
var reader = new StreamReader(File.OpenRead(filePath));
while (!reader.EndOfStream)
{
List<string> listA = new List<string>();
string line = reader.ReadLine();
mList.Add(line );
}
}
int i = 0;
int n = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (n > 20)
n = 0;
int j=0;
chart.Series["Tags"].Points.Clear();
for (i=n; i < mList.Count; i++)
{
string l =mList[i];
chart.Series["Tags"].Points.AddY(l);
j++;
if (j == 10)
break;
}
n++;
chart.Update();
}
List<List<string>> mList = new List<List<string>>();

C# how to check if all array elements are visible

My program creates 5 different labels with a cube form and they just drop down. When I press on them, they come invisible. I want to check if all of them are invisible, but don't know how to do so. Tried going through this site, found a solution with bool, but it just doesn't work my way. Also when my labels appear,you can see only 4 of them.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Label [] kubeliai = new Label [5];
int poz = 100;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < kubeliai.Length; i++)
{
kubeliai[i] = new Label();
Controls.Add(kubeliai[i]);
Random pos = new Random();
kubeliai[i].Top = 50;
kubeliai[i].Left = poz;
poz += pos.Next(50, 200);
kubeliai[i].BackColor = Color.Red;
kubeliai[i].Height = 20;
kubeliai[i].Width = 20;
kubeliai[i].Click += new EventHandler(kubelio_clickas);
}
Timer kritimo_laikrodis = new Timer();
kritimo_laikrodis.Interval = 10;
kritimo_laikrodis.Tick += new EventHandler(laikrodis);
kritimo_laikrodis.Enabled = true;
}
void kubelio_clickas (object sender, EventArgs e)
{
((Label)sender).Visible = false;
}
void laikrodis (object sender, EventArgs e)
{
for (int i = 0; i < kubeliai.Length; i++)
{
kubeliai[i].Top += 1;
if (kubeliai.All.Visible == false) // this is an error
{
kubeliai[i].Visible = true;
kubeliai[i].Top = 50;
Random pos = new Random();
poz += pos.Next(50, 200);
}
}
}
Using Linq you can check if all are invisible in this way
var areAllInvisible = kubeliai.All(l => l.Visible == false);
if (areAllInvisible)
{
// do something
}
when my labels appear you can see only 4 of them.
That's because the way you are picking random numbers is picking the same numbers each time and you are therefore placing your labels on top of each other. Read the first paragraph of the Random() documentation:
Different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.
Use new Random() once in your class definition like this:
Label [] kubeliai = new Label [5];
Random pos = new Random();
And remove it everywhere else in your program.

MsChart - Rangebar marker at a specific value

I just can't find a way to add a marker at a specific value on a range bar MsChart.
Let's say we have a simple range bar graph with 1 serie and 1 point. The point has 2 Y values (ex: 5-20). How can you show a triangle marker at 15?
Thank you.
Try this:
private void Form1_Load(object sender, EventArgs e)
{
DataPoint dp1 = new DataPoint(1, new double[] { 5, 15 });
dp1.MarkerStyle = MarkerStyle.Triangle;
dp1.MarkerSize = 12;
dp1.MarkerColor = Color.Red;
DataPoint dp2 = new DataPoint(1, new double[] { 15, 20 });
chart1.Series[0].Points.Add(dp1);
chart1.Series[0].Points.Add(dp2);
}
You can make two chart areas and put them on top of eachother. Make the second chartarea backcolor transparent.
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
chart1.ChartAreas[0].Position = new ElementPosition(0, 0, 100, 100);
Series s1 = new Series();
s1.ChartType = SeriesChartType.RangeBar;
s1.Points.AddXY(2, 2);
s1.Points.AddXY(1, 1);
chart1.Series.Add(s1);
ChartArea ca2 = new ChartArea();
chart1.ChartAreas.Add(ca2);
ca2.Position = new ElementPosition(0, 0, 100, 100);
ca2.BackColor = Color.Transparent;
Series s2 = new Series();
s2.ChartType = SeriesChartType.Point;
s2.MarkerStyle = MarkerStyle.Triangle;
s2.MarkerSize = 10;
s2.Points.AddXY(2, 2);
s2.ChartArea = ca2.Name;
chart1.Series.Add(s2);
}

C#: How to change the color of specific lines in a chart?

I do not want to change the whole series like this:
chart1.Series["test1"].Color = Color.Red;
Instead, I want to change the color of individual lines, like this:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
var r = new Random();
int i = chart1.Series["test1"].Points.AddXY(r.Next(0, 10), r.Next(0, 10));
try
{
chart1.Series["test1"].Points[i - 1].Color = Color.LightPink;
chart1.Series["test1"].Points[i - 2].Color = Color.LightPink;
chart1.Series["test1"].Points[i - 3].BorderDashStyle = ChartDashStyle.Dash;
chart1.Series["test1"].Points[i - 4].BorderDashStyle = ChartDashStyle.Dash;
chart1.Series["test1"].Points.RemoveAt(i - 5);
}
catch { }
}
However, this is not working and I don't understand why.
The problem was that the SeriesChartType was set to FastLine instead of just Line.
This doesn't work:
chart1.Series["test1"].ChartType = SeriesChartType.FastLine;
This works:
chart1.Series["test1"].ChartType = SeriesChartType.Line;

Categories