The graph resizes and becomes smaller on every function call - c#

I have a function that I need to call every once in a while. But, every time I do, the graph (a pie chart) resizes itself and becomes smaller than the previously obtained piechart.
void LoadPieChart(DateTime lower, DateTime higher)
{
splitContainer1.Panel1.Controls.Remove(pieChart);
pieChart.Series.Clear();
pieChart.Palette = ChartColorPalette.Fire;
pieChart.BackColor = Color.Black;
pieChart.Titles.Add("LOST OPPORTUNITY");
pieChart.ChartAreas[0].BackColor = Color.Transparent;
Series series1 = new Series
{
Name = "series1",
IsVisibleInLegend = true,
Color = System.Drawing.Color.White,
ChartType = SeriesChartType.Pie
};
pieChart.Series.Add(series1);
int num = A.CountLO();
List<string>[] lista = new List<string>[7];
lista = A.SelectLO();
float counter_manpower = 0;
float counter_spares = 0;
float counter_tools = 0;
float counter_other = 0;
string[] reason = lista[6].ToArray();
string[] low = lista[4].ToArray();
string[] up = lista[5].ToArray();
string[] collection = new string[366];
for (int j = num-LO; j < num; j++)
{
DateTime x = DateTime.Parse(low[j]);
DateTime y = DateTime.Parse(up[j]);
if (x.Date>=lower.Date && y.Date<=higher.Date)
{
if (reason[j].Equals("LACK OF MANPOWER"))
counter_manpower++;
if (reason[j].Equals("LACK OF SPARES"))
counter_spares++;
if (reason[j].Equals("LACK OF TOOLS"))
counter_tools++;
if (!reason[j].Equals("LACK OF MANPOWER") && !reason[j].Equals("LACK OF SPARES") && !reason[j].Equals("LACK OF TOOLS"))
{
counter_other++;
}
}
}
float a = ((counter_manpower/(counter_manpower+counter_spares+counter_tools+counter_other))*100);
float b = ((counter_spares / (counter_manpower + counter_spares + counter_tools+counter_other)) * 100);
float c = ((counter_tools / (counter_manpower + counter_spares + counter_tools+counter_other)) * 100);
float d = ((counter_other / (counter_manpower + counter_spares + counter_tools + counter_other)) * 100);
double aa = Math.Truncate(100 * a) / 100;
double bb = Math.Truncate(100 * b) / 100;
double cc = Math.Truncate(100 * c) / 100;
double dd = Math.Truncate(100 * d) / 100;
series1.Points.Add(counter_manpower);
var p1 = series1.Points[0];
Math.Round(a, 1);
Math.Round(b, 1);
Math.Round(c, 1);
if (counter_manpower!=0)
p1.AxisLabel = (aa.ToString() + "%");
p1.LegendText = "LACK OF MANPOWER";
p1.Color = Color.Red;
series1.Points.Add(counter_spares);
p1 = series1.Points[1];
if (counter_spares!=0)
p1.AxisLabel = (bb.ToString() + "%");
p1.LegendText = "LACK OF SPARES";
p1.Color = Color.Yellow;
series1.Points.Add(counter_tools);
p1 = series1.Points[2];
if(counter_tools!=0)
p1.AxisLabel = (cc.ToString() + "%");
p1.LegendText = "LACK OF TOOLS";
p1.Color = Color.Orange;
series1.Points.Add(counter_other);
p1 = series1.Points[3];
p1.AxisLabel = (dd.ToString() + "%");
p1.LegendText = "OTHER";
p1.Color = Color.Maroon;
//pieChart.Invalidate();
splitContainer1.Panel1.Controls.Add(pieChart);
}
I can't seem to find out why, any suggestions?
I use the following function to initalize the graph:
private void InitializeChart()
{
this.components = new System.ComponentModel.Container();
ChartArea chartArea1 = new ChartArea();
Legend legend1 = new Legend() { BackColor = Color.White, ForeColor = Color.Black, Title = "CAUSE" };
pieChart = new Chart();
((ISupportInitialize)(pieChart)).BeginInit();
SuspendLayout();
//===Pie chart
chartArea1.Name = "PieChartArea";
pieChart.ChartAreas.Add(chartArea1);
pieChart.Dock = System.Windows.Forms.DockStyle.Fill;
legend1.Name = "Legend1";
pieChart.Legends.Add(legend1);
pieChart.Location = new System.Drawing.Point(0, 50);
//====Bar Chart
AutoScaleDimensions = new System.Drawing.Size(284,262);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
//this.ClientSize = new System.Drawing.Size(284, 262);
this.Load += new EventHandler(Form1_Load);
((ISupportInitialize)(this.pieChart)).EndInit();
this.ResumeLayout(false);
}

I'm not sure where pieChart is defined... a private field?? If so, try creating a new PieChart after you have removed the previous one from the container:
splitContainer1.Panel1.Controls.Remove(pieChart);
pieChart = new PieChart();
pieChart.Series.Clear();
I'm guessing somewhere in your code you are accumulating a value instead of assigning it, so it is getting progressively smaller as you call the function on the same PieChart. Clearing out the pieChart should fix this problem.

Related

C#/ Visual studio 2019 || windows form autoscroll flickering

I am trying to make a Windows Form that shows display data from data a table. Every thing is working fine until I start scrolling in the Form using the auto scroll property.
I don't know why that's happening. I hope someone can help me.
private void allShowsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
// Load All the Shows from the database
DataTable dt = accesse.LoadAllShows();
// Create the allShows From
Form allShows = new Form();
// Create the Controls for the AllShows form.
PictureBox[] pic = new PictureBox[dt.Rows.Count];
Label[] showName = new Label[dt.Rows.Count], season = new Label[dt.Rows.Count], eps = new Label[dt.Rows.Count], typ = new Label[dt.Rows.Count];
TextBox[] txtShowName = new TextBox[dt.Rows.Count], txtSeason = new TextBox[dt.Rows.Count], txtEps = new TextBox[dt.Rows.Count], txtTyp = new TextBox[dt.Rows.Count];
// AllShows Form properties
allShows.BackColor = Color.White;
allShows.Font = new Font("Calibri", 14f, FontStyle.Regular);
allShows.ForeColor = Color.Black;
allShows.Size = new Size(1050, 700);
allShows.StartPosition = FormStartPosition.CenterScreen;
allShows.AutoScroll = true;
allShows.AutoScrollMargin = new Size(0, 18);
// Variables
int y = 325; // the distens bettwen the controls on the Y and X.
bool xTurn = false; // the axies turn.
int yTurnNum = 0; // the y turn number.
for (int i = 0; i < dt.Rows.Count; i++)
{
// PictureBox Poster Properties
pic[i] = new PictureBox();
pic[i].BorderStyle = BorderStyle.FixedSingle;
pic[i].Size = new Size(162, 288);
pic[i].SizeMode = PictureBoxSizeMode.StretchImage;
pic[i].Image = Image.FromFile(dt.Rows[i][4].ToString());
// Label showName Properties
showName[i] = new Label();
showName[i].Text = "Show Name: " + dt.Rows[i][0];
showName[i].AutoSize = true;
// Label Season Properties
season[i] = new Label();
season[i].Text = "Season: " + dt.Rows[i][1];
season[i].AutoSize = true;
// Label Eps Properties
eps[i] = new Label();
eps[i].Text = "Episodes: " + dt.Rows[i][2];
eps[i].AutoSize = true;
// Label Typ Properties
typ[i] = new Label();
typ[i].Text = "Typ: " + dt.Rows[i][3];
typ[i].AutoSize = true;
if (xTurn)
{
// Sitting the location of the controls on the X turn
pic[i].Location = new Point(515, pic[i - 1].Location.Y);
showName[i].Location = new Point(687, showName[i - 1].Location.Y);
season[i].Location = new Point(687, season[i - 1].Location.Y);
eps[i].Location = new Point(687, eps[i - 1].Location.Y);
typ[i].Location = new Point(687, typ[i - 1].Location.Y);
xTurn = false;
}
else
{
// Sitting the location of the controls on the Y turn
pic[i].Location = new Point(15, 15 + (yTurnNum * y));
showName[i].Location = new Point(187, 20 + (yTurnNum * y));
season[i].Location = new Point(187, 55 + (yTurnNum * y));
eps[i].Location = new Point(187, 90 + (yTurnNum * y));
typ[i].Location = new Point(187, 125 + (yTurnNum * y));
yTurnNum += 1;
xTurn = true;
}
allShows.Controls.Add(pic[i]);
allShows.Controls.Add(showName[i]);
allShows.Controls.Add(season[i]);
allShows.Controls.Add(eps[i]);
allShows.Controls.Add(typ[i]);
}
allShows.ShowDialog();
}
catch (Exception ex)
{
tools.ShowErrorMessageBox(ex.Message, "Error");
}
}
I hope this gif will help you to understand what is happening.
enter image description here

MS Gantt Chart 2 Axis

I had Gantt chart like this. I'd like to show AxisX2 with value is percentage that I prepared formula for it. I had challenges to show AxisX2 and set series for it.
Here is the Gantt chart I captured click here.
I expect to one more axis like this.
Please help, Thank you .
Here are some basic function to render that chart
public void setUpGantt(Chart chart)
{
chart.Series.Clear();
Series s = chart.Series.Add("sszs");
s.ChartType = SeriesChartType.RangeBar;
s.YValueType = ChartValueType.DateTime;
s.ResetIsVisibleInLegend () ;
s.IsVisibleInLegend = true;
Axis ax = chart.ChartAreas[0].AxisX;
Axis ay = chart.ChartAreas[0].AxisY;
ax.MajorGrid.Enabled = false;
ay.IntervalType = DateTimeIntervalType.Minutes;
ay.Interval = 60;
ay.LabelStyle.Format = "HH:mm";
ay.Minimum = 0;
ay.Maximum = 0.2;
limitGantt(chart, "0:00", "24:00");
s.ToolTip = "#VALY1{HH:mm}~#VALY2{HH:mm}";
}
public void limitGantt(Chart chart, string start, string end)
{
Axis ax = chart.ChartAreas[0].AxisX;
Axis ay = chart.ChartAreas[0].AxisY;
ay.Minimum = fromTimeString(start).ToOADate();
ay.Maximum = fromTimeString(end).ToOADate();
}
DateTime fromTimeString(string time)
{
var p = time.Split(':');
int sec = p.Length == 3 ? Convert.ToInt16(p[2]) : 0;
TimeSpan t = new TimeSpan(Convert.ToInt16(p[0]), Convert.ToInt16(p[1]), sec);
return DateTime.Today.Add(t);
}
public void addGanttTask(Series s, string start, string end, Color c, int slot, string [] array)
{
DateTime start_ = fromTimeString(start);
DateTime end_ = fromTimeString(end);
int pt = s.Points.AddXY(slot, start_, end_);
s.Points[pt].Color = c;
s.IsVisibleInLegend = true;
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
if (slot == i + 1)
{ s.Points[pt].AxisLabel = array[i];
}
}
}
}
Taw's comment
public void setUpGantt(Chart chart)
{
chart.Series.Clear();
Series s = chart.Series.Add("sszs");
s.ChartType = SeriesChartType.RangeBar;
s.YValueType = ChartValueType.DateTime;
s.ResetIsVisibleInLegend () ;
s.IsVisibleInLegend = true;
Axis ax = chart.ChartAreas[0].AxisX;
Axis ay = chart.ChartAreas[0].AxisY;
ax.MajorGrid.Enabled = false;
Axis ax2 = chart.ChartAreas[0].AxisX2;
ax2.Enabled = AxisEnabled.True;
ax2.Maximum = 100;
ax2.MajorGrid.Enabled = false;
ay.IntervalType = DateTimeIntervalType.Minutes;
ay.Interval = 60;
ay.LabelStyle.Format = "HH:mm";
ay.Minimum = 0;
ay.Maximum = 0.2;
limitGantt(chart, "0:00", "24:00");
s.ToolTip = "#VALY1{HH:mm}~#VALY2{HH:mm}";
}
I'd like to have percentage = Green Time/Total time (from 00:
00 to Current time) example
Thank you for TaW's suggestion. It worked for me.
I post here to share who want to know
public void setUpGantt(Chart chart)
{
chart.Series.Clear();
Series s = chart.Series.Add("sszs");
s.ChartType = SeriesChartType.RangeBar;
s.YValueType = ChartValueType.DateTime;
s.ResetIsVisibleInLegend () ;
s.IsVisibleInLegend = true;
Axis ax = chart.ChartAreas[0].AxisX;
Axis ay = chart.ChartAreas[0].AxisY;
ax.MajorGrid.Enabled = false;
Axis ax2 = chart.ChartAreas[0].AxisX2;
ax2.Enabled = AxisEnabled.True;
ax2.MajorGrid.Enabled = true;
ax2.CustomLabels.Clear();// clear previous value when switch another data
for (int i = 0; i < 12; i++)
{
CustomLabel cl = new CustomLabel();
cl.FromPosition = i+0.5;
cl.ToPosition = i+1.5;
cl.Text = i+" %"; // example value to show on CustomLabel
ax2.CustomLabels.Add(cl);
}
ay.IntervalType = DateTimeIntervalType.Minutes;
ay.Interval = 60;
ay.LabelStyle.Format = "HH:mm";
ay.Minimum = 0;
ay.Maximum = 0.2;
limitGantt(chart, "0:00", "24:00");
s.ToolTip = "#VALY1{HH:mm}~#VALY2{HH:mm}";
}
The main script to show one more Axis with CustomLabel
Axis ax2 = chart.ChartAreas[0].AxisX2;
ax2.Enabled = AxisEnabled.True;
ax2.MajorGrid.Enabled = true;
ax2.CustomLabels.Clear();// clear previous value when switch another data
for (int i = 0; i < 12; i++)
{
CustomLabel cl = new CustomLabel();
cl.FromPosition = i+0.5;
cl.ToPosition = i+1.5;
cl.Text = i+" %"; // example value to show on CustomLabel
ax2.CustomLabels.Add(cl);
}

Add panels dynamically to form

I'm trying to add panels to a form according to the ids quantity that is received. At running, the panels are added to the form, but only the first one has the controls, and I don't get why.
This is my actual code:
private void loadItems(List<int> ids)
{
int id = 0,
panelX = 10,
panelY = -30,
itemslblX = 15,
itemslblY = -65,
IDtxtX = 360,
IDtxtY = -40,
nametxtX = 130,
nametxtY = -40;
int height = (80 * ids.Count) + 50;
this.Size = new Size(600,height);
foreach(int c in ids)
{
panelY = panelY + 80;
itemslblY = itemslblY + 80;
terrainMenuY = terrainMenuY + 80;
IDtxtY = IDtxtY + 80;
nametxtY = nametxtY + 80;
Panel panel = new Panel();
panel.Location = new Point(panelX, panelY);
panel.Dock = DockStyle.None;
panel.Height = 75;
panel.Width = 575;
panel.BackColor = Color.Gray;
panel.Name = ids[id]+"Panel".ToString();
Label itemslbl = new Label();
itemslbl.Location = new Point(itemslblX, itemslblY);
itemslbl.Text = "Imagen Nombre ID";
itemslbl.Height = 20;
itemslbl.Width = 550;
itemslbl.Name = ids[id] + "itemsLabel".ToString();
TextBox IDtxt = new TextBox();
IDtxt.Location = new Point(IDtxtX, IDtxtY);
IDtxt.Height = 27;
IDtxt.Width = 200;
IDtxt.Text = ids[id].ToString();
IDtxt.ReadOnly = true;
IDtxt.Name = ids[id] + "IDtext".ToString();
TextBox nametxt = new TextBox();
nametxt.Location = new Point(nametxtX, nametxtY);
nametxt.Height = 27;
nametxt.Width = 200;
nametxt.ReadOnly = true;
nametxt.Name = ids[id] + "nameText".ToString();
panel.Controls.Add(itemslbl);
panel.Controls.Add(nametxt);
panel.Controls.Add(IDtxt);
this.Controls.Add(panel);
id++;
}
}
Any advice, please, and thanks for your time.

i need audio frequency response graph c#

i need logarithm x-axis based linechart for audio frequency magnitude response for c# winform , i have tested default chart and livechart but c'ant align x axis attached photo like . anybody know please help me.
sorry for my bad english
Live Chart Code :
cartesianChart1.AxisY.Add(new Axis
{
Title = "Gain",
MaxValue = 10,
MinValue = -15,
Separator = new Separator
{
Stroke = new SolidColorBrush(System.Windows.Media.Color.FromRgb(46, 35, 35))
}
});
cartesianChart1.AxisX.Add(new LogarithmicAxis
{
Title = "Freq",
LabelFormatter = (value) => (Math.Pow(10, value).ToString("N0")+"Hz"),
Base = 10,
Separator = new Separator
{
Step=0,
Stroke = new SolidColorBrush(System.Windows.Media.Color.FromRgb(35, 35, 35))
},
});
cartesianChart1.BackColor = System.Drawing.Color.FromArgb(0, 0, 0);
cartesianChart1.DisableAnimations = true;
cartesianChart1.Hoverable = false;
cartesianChart1.DataTooltip = null;
var Datapoint = new ChartValues<ObservablePoint>{
new ObservablePoint(1, 5),
new ObservablePoint(5, -4),
new ObservablePoint(10, 6),
new ObservablePoint(100, 4),
new ObservablePoint(150, 7),
new ObservablePoint(1000, 2),
new ObservablePoint(10000, 8),
new ObservablePoint(15000, 2),
new ObservablePoint(20000, -7),
};
cartesianChart1.Series = new SeriesCollection(Mappers.Xy<ObservablePoint>()
.X(point => Math.Log10(point.X))
.Y(point => point.Y))
{
new LineSeries
{
PointGeometry = null,
PointGeometrySize = 0,
Values = Datapoint,
}
};
Live Chart Display :
Default Chart Code :
var r = new Random();
float val;
var chart = chart1.ChartAreas[0];
chart.AxisX.IntervalType = DateTimeIntervalType.Number;
chart.AxisX.LabelStyle.Format = "";
chart.AxisY.LabelStyle.Format = "";
chart.AxisY.LabelStyle.IsEndLabelVisible = true;
chart.AxisX.Minimum = 0;
chart.AxisX.Maximum = 20000;
chart.AxisY.Minimum = -15;
chart.AxisY.Maximum = 10;
chart.AxisX.Interval = 500;
chart.AxisY.Interval = 3;
chart.BackColor = Color.Black;
chart1.Series.Add("Sakthi");
chart1.Series["Sakthi"].ChartType = SeriesChartType.Spline;
chart1.Series["Sakthi"].Color = Color.Yellow;
chart1.Series["Sakthi"].BorderWidth = 3;
chart1.Series["Sakthi"].BorderColor = Color.Black;
chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.FromArgb(35, 35, 35);
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.FromArgb(35, 35, 35);
chart1.ChartAreas[0].AxisY.LabelStyle.ForeColor = Color.White;
chart1.ChartAreas[0].AxisX.LabelStyle.ForeColor = Color.White;
chart1.Legends[0].Enabled = false;
chart.AxisY.StripLines.Add(new StripLine
{
BorderDashStyle = ChartDashStyle.Dot,
BorderColor = Color.White,
StripWidth = 0
});
chart1.Series.Clear();
chart1.Series.Add("Sakthi");
chart1.Series["Sakthi"].ChartType = SeriesChartType.Spline;
chart1.Series["Sakthi"].Color = Color.Yellow;
chart1.Series["Sakthi"].BorderWidth = 3;
chart1.Series["Sakthi"].BorderColor = Color.Black;
for (int i = 0; i < 10; i++)
{
val = r.Next(-15, 10);
chart1.Series["Sakthi"].Points.AddXY(i*2000, val);
}
Default Chart Display :
i want this this type x axis label :

Axes labels in chart using dual Y axes are reversed?

I have a chart that shows two distinct Y values for the same DateTime X values. I am graphing them using a Spline on the same chart area with primary and secondary Y axes. The graph seems to work correctly with the exception that the Y axis labels are swapped. The expected primary Y axes labels are on the secondary axis and vice-versa.
Also, it should be noted that the charts are never displayed on screen, they are saved as image files in the file system and in a database using the chart.SaveImage method.
Here is an image of the output of the chart:
Here is the code to generate the chart:
// create the chart
Chart chart = new Chart();
chart.Size = new Size(width, height);
chart.AntiAliasing = AntiAliasingStyles.All;
string datatype = data[0].DataType;
string datatype2 = data2[0].DataType;
SampleUnit unit = GetSampleUnit(data[0].Unit);
string u = "";
if (unit != null)
{
u = unit.ShortName;
}
SampleUnit unit2 = GetSampleUnit(data2[0].Unit);
string u2 = "";
if (unit2 != null)
{
u2 = unit2.ShortName;
}
var chartArea = new ChartArea();
chartArea.AxisX.LabelStyle.Format = "dd MMM\nHH:mm";
chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
chartArea.AxisX.LabelStyle.Font = new Font("Calibri", 8);
chartArea.AxisY.LabelStyle.Font = new Font("Calibri", 8);
chartArea.AxisY2.LabelStyle.Font = new Font("Calibri", 8);
chartArea.AxisY2.Enabled = AxisEnabled.True;
chartArea.AxisY2.MajorGrid.Enabled = false;
if (string.IsNullOrEmpty(u))
{
chartArea.AxisY.Title = datatype;
}
else
{
chartArea.AxisY.Title = datatype + " (" + u + ")";
}
if (string.IsNullOrEmpty(u2))
{
chartArea.AxisY2.Title = datatype2;
}
else
{
chartArea.AxisY2.Title = datatype2 + " (" + u2 + ")";
}
chartArea.AxisY.TitleForeColor = Color.MediumBlue;
chartArea.AxisY2.TitleForeColor = Color.Red;
chart.ChartAreas.Add(chartArea);
var series = new Series();
series.Name = datatype;
series.ChartType = SeriesChartType.Spline;
series.XValueType = ChartValueType.DateTime;
series.YValueType = ChartValueType.Double;
series.YAxisType = AxisType.Primary;
series.Color = Color.MediumBlue;
chart.Series.Add(series);
var series2 = new Series();
series2.Name = datatype2;
series2.ChartType = SeriesChartType.Spline;
series2.XValueType = ChartValueType.DateTime;
series2.YValueType = ChartValueType.Double;
series.Color = Color.Red;
series.YAxisType = AxisType.Secondary;
chart.Series.Add(series2);
chart.Titles.Add(sensor.Name + " " + char.ToUpper(datatype[0]) + datatype.Substring(1) + " " + char.ToUpper(datatype2[0]) + datatype2.Substring(1));
// bind the datapoints
chart.Series[datatype].Points.DataBindXY(data, "Timestamp", data, "Value");
chart.Series[datatype2].Points.DataBindXY(data2, "Timestamp", data2, "Value");
// draw!
chart.Invalidate();
So, I have two questions:
Why are the axis labels reversed?
Cosmetic: Why is the axis title putting a bar "|" at the end instead of a closing parenthesis ")"? Is this just a visual artifact from saving the chart as an image?
You have a cut-n-paste typo
change
series.Color = Color.Red;
series.YAxisType = AxisType.Secondary;
to
series2.Color = Color.Red;
series2.YAxisType = AxisType.Secondary;

Categories

Resources