Plot zedgraph direction - c#

I trying make a zedgraph plotter system in C# in the temperature measurement system, and successfully to graph serial data. But the direction is not linear, it's mean the lower temperature not placed in the first time but in the end of time. This is my code:
private void initCurves()
{
PointPairList list1 = new PointPairList();
PointPairList list2 = new PointPairList();
PointPairList list3 = new PointPairList();
Samples = 10000;
NoOfCurves = 3;
// Samples = int.Parse(XTextBox.Text);
// NoOfCurves = (int)NoOfDataNumericUpDown.Value;
for (int j = 0; j < NoOfCurves; j++)
{
PointPairList tempppl = new PointPairList();
for (double x = 0; x < Samples; x++)
{
tempppl.Add(x, -1);
}
list1.Add(tempppl);
list2.Add(tempppl);
list3.Add(tempppl);
}
// Generate a red curve with diamond
// symbols, and "Porsche" in the legend
ZedGraphControl1.GraphPane.AddCurve("Thermocouple #1",list1, Color.Red, SymbolType.None);
ZedGraphControl1.GraphPane.AddCurve("Thermocouple #2", list2, Color.Blue, SymbolType.None);
ZedGraphControl1.GraphPane.AddCurve("Thermocouple #3", list3, Color.Brown, SymbolType.None);
// Tell ZedGraph to refigure the
// axes since the data have changed
ZedGraphControl1.AxisChange();
}
private void Form1_Load(object sender, EventArgs e) {
//Array of baud rates
string[] baudrates = {"75", "110", "134", "150", "300", "600", "1200", "1800",
"2400", "4800", "7200", "9600", "14400", "19200", "38400",
"57600", "115200", "128000"};
//Set data source for baud rate combobox
COMBaudComboBox.DataSource = baudrates;
// Set the titles and axis labels
GraphPane myPane = ZedGraphControl1.GraphPane;
//Set title axis labels and font color
myPane.Title.Text = "Temperature vs. Time";
myPane.Title.FontSpec.FontColor = Color.Black;
myPane.XAxis.Title.Text = "Time (Sec)";
myPane.XAxis.Title.FontSpec.FontColor = Color.Black;
myPane.YAxis.Title.Text = "Temperature (Celcius)";
myPane.YAxis.Title.FontSpec.FontColor = Color.Black;
//Fill the chart background with a color gradient
myPane.Fill = new Fill(Color.FromArgb(255, 255, 245), Color.FromArgb(255, 255, 190), 90F);
myPane.Chart.Fill = new Fill(Color.FromArgb(255, 255, 245), Color.FromArgb(255, 255, 190), 90F);
myPane.XAxis.Scale.FontSpec.IsAntiAlias = true;
myPane.YAxis.Scale.FontSpec.IsAntiAlias = true;
//Add grid lines to the plot and make them gray
myPane.XAxis.MajorGrid.IsVisible = true;
myPane.XAxis.MajorGrid.Color = Color.LightGray;
myPane.YAxis.MajorGrid.IsVisible = true;
myPane.YAxis.MajorGrid.Color = Color.LightGray;
//Enable point value tooltips and handle point value event
ZedGraphControl1.IsShowPointValues = true;
ZedGraphControl1.PointValueEvent += new ZedGraphControl.PointValueHandler(PointValueHandler);
//Show the horizontal scroll bar
ZedGraphControl1.IsShowHScrollBar = true;
//Automatically set the scrollable range to cover the data range from the curves
ZedGraphControl1.IsAutoScrollRange = true;
//Add 10% to scale range
ZedGraphControl1.ScrollGrace = 0.1;
//Horizontal pan and zoom allowed
ZedGraphControl1.IsEnableHPan = true;
ZedGraphControl1.IsEnableHZoom = true;
//Vertical pan and zoom not allowed
ZedGraphControl1.IsEnableVPan = false;
ZedGraphControl1.IsEnableVZoom = false;
//Set the initial viewed range
// ZedGraphControl1.GraphPane.XAxis.Scale.MinAuto = true;
// ZedGraphControl1.GraphPane.XAxis.Scale.MaxAuto = true;
//Let Y-Axis range adjust to data range
ZedGraphControl1.GraphPane.IsBoundedRanges = true;
//Set the margins to 10 points
myPane.Margin.All = 10;
//Hide the legend
// myPane.Legend.IsVisible = false;
//Set start point for XAxis scale
myPane.XAxis.Scale.BaseTic = 0;
//Set start point for YAxis scale
myPane.YAxis.Scale.BaseTic = 0;
//Set max/min XAxis range
myPane.XAxis.Scale.Min = 0.0;
// myPane.XAxis.Scale.Max = 7200;
myPane.XAxis.Scale.MinorStep = 5;
myPane.XAxis.Scale.MajorStep = 10;
//Set max/min YAxis range
myPane.YAxis.Scale.Min = 0;
myPane.YAxis.Scale.Max = 400;
myPane.YAxis.Scale.MinorStep = 5;
myPane.YAxis.Scale.MajorStep = 10;
RollingPointPairList list = new RollingPointPairList(7400);
//Initially, a curve is added with no data points (list is empty)
//Color is red, and there will be no symbols
//LineItem curve = myPane.AddCurve("Temperature", list, Color.Red, SymbolType.None);
//Scale the axis
myPane.AxisChange();
// Set defaults for UI
SpeedNumericUpDown.Value = Properties.Settings.Default.SpeedSetting;
NoOfDataNumericUpDown.Value = Properties.Settings.Default.DataSetsSetting;
XTextBox.Text = Properties.Settings.Default.XScaleSetting;
YTextBox.Text = Properties.Settings.Default.YScaleSetting;
SeriesLineSizeNumericUpDown.Value = Properties.Settings.Default.LineSizeSetting;
// Fill COMPortComboBox with available COM ports
string[] aosPorts = SerialPort.GetPortNames();
bool foundCOMPortFlag = false;
COMPortComboBox.DataSource = aosPorts;
foreach (string port in aosPorts) {
if (port == Properties.Settings.Default.COMPortSetting) {
COMPortComboBox.Text = port;
foundCOMPortFlag = true;
}
}
// We didn't find the COM port, so set to COM1
if (foundCOMPortFlag == false) {
COMPortComboBox.SelectedIndex = 0;
}
}
can I change the plot graph direction to be linear? how I can do that?
Thanks for your help
regards
Nanang
The Picture of Result Plot graph and wish plot graph

Related

How to print C# chart with more pages

I have C# project already done but im having issue with printing it's charts when comes out with more pages of data points, i got the scroll bar work when start getting more pages so the user can review all data on all pages but i could not find how to make the print preview shows them or print them,
when click on print, it shows only the first page on the print preview and same thing when print it out.
her is the print code:
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = this.chart1.Printing.PrintDocument;
((Form)ppd).WindowState = FormWindowState.Maximized;
chart1.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Left = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Right = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Top = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Bottom = 0;
ppd.ShowDialog();
and here is the chart load code:
public void loadChart(string sqlvalue)//load chart method
{
chart1.ChartAreas[0].AxisY.Maximum = 55;
chart1.ChartAreas[0].AxisY.Minimum = 35;
chart1.ChartAreas[0].AxisY.Interval = 5;//control how many lines/Interval
chart1.ChartAreas[0].AxisY.ScrollBar.Enabled = true;
chart1.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.Minimum = 0;
// chart1.ChartAreas[0].AxisX.Maximum = 10;
chart1.ChartAreas[0].AxisX.Interval = 1;
//X AXES label angle
chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 60;
da = new SqlDataAdapter(sqlvalue, cn.connect());
da.Fill(dt);
this.chart1.DataSource = dt;
this.chart1.Series["left"].XValueMember = dt.Columns[3].ToString();//date data
this.chart1.Series["left"].YValueMembers = dt.Columns[1].ToString();//spindle 1 data
this.chart1.Series["Right"].YValueMembers = dt.Columns[2].ToString();//spindle 2 data
//label the series lines, Backcolor and forcolor
chart1.Series[0].LabelBackColor = Color.Red;
chart1.Series[0].LabelForeColor = Color.White;
//datapoint marker's color, bordercolor,style and size
chart1.Series[0].MarkerColor = Color.White;
chart1.Series[0].MarkerBorderColor = Color.Black;
chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
chart1.Series[0].MarkerSize = 8;
//datapoint marker's color, style and size
chart1.Series[1].MarkerColor = Color.White;
chart1.Series[1].MarkerBorderColor = Color.Black;
chart1.Series[1].MarkerStyle = MarkerStyle.Circle;
chart1.Series[1].MarkerSize = 8;
chart1.Series[1].LabelBackColor = Color.Blue;
chart1.Series[1].LabelForeColor = Color.White;
//Chart background lines color
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Silver;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Silver;
this.chart1.DataBind();
cn.disconnect();
// enable autoscroll
chart1.ChartAreas[0].CursorX.AutoScroll = true;//------------
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoom(0, 15);
chart1.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
// set scrollbar small change to the target size
chart1.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = 15;
Legend left = new Legend();
Legend LC = CustomCloneLegend(chart1, left);
chart1.Legends.Add(LC);
chart1.Padding = Padding.Empty;
ChartArea CA = chart1.ChartAreas[0];
CA.Position = new ElementPosition(4,6, 100, 90);
}
Thank you for your time and help, here is the chart code update:
private static Image MergeImages(List<Image> imageList)
{
var finalSize = new Size();
foreach (var image in imageList)
{
if (image.Width > finalSize.Width)
{
finalSize.Width = image.Width;
}
finalSize.Height += image.Height;
}
var outputImage = new Bitmap(finalSize.Width, finalSize.Height);
using (var gfx = Graphics.FromImage(outputImage))
{
var y = 0;
foreach (var image in imageList)
{
gfx.DrawImage(image, 0, y);
y += image.Height;
}
}
return outputImage;
}
The second method:
List<Image> ChartsToImages(List<Chart> charts)
{
var imageList = new List<Image>();
foreach (var c in charts)
{
using (var ms = new MemoryStream())
{
c.SaveImage(ms, ChartImageFormat.Png);
var bmp = System.Drawing.Bitmap.FromStream(ms);
imageList.Add(bmp);
}
}
return imageList;
}
and this code
var chartList = new List<Chart> { chart1 };
var imageList = ChartsToImages(chartList);
var finalImage = MergeImages(imageList);
finalImage.Save("D:\\Junk.png", ImageFormat.Png);
Im not sure is that what you mean by your first comment, but i found this code here under Converting chart to image questions. this code convert and saves the chart in the same amount of pages but i need to show them in the printpreviewcontrol and print them.
Below code refers to the as per page count starting point and ending point based printing. And Grid view value chars are row loop based counting the page.
private int numberOfItemsPerPage = 0;
private int numberOfItemsPrintedSoFar = 0;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int height = 480; //page height stating point
for (int l = numberOfItemsPrintedSoFar; l < dataGridView2.Rows.Count; l++)
{
numberOfItemsPerPage = numberOfItemsPerPage + 1;
if (numberOfItemsPerPage <= 25) // 25 is Page Line Item
{
numberOfItemsPrintedSoFar++;
if (numberOfItemsPrintedSoFar <= dataGridView2.Rows.Count)
{
height += dataGridView2.Rows[0].Height;
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[0].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(5, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[1].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(170, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[2].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(290, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[3].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(345, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
}
else
{
e.HasMorePages = false;
}
}
else
{
numberOfItemsPerPage = 0;
e.HasMorePages = true;
return;
}
}
numberOfItemsPerPage = 0;
numberOfItemsPrintedSoFar = 0;
}

How Do I Get The Scale of The Secondary Axis to be Based on My Series Values?

I'm using System.Web.UI.DataVisualization. Charting to create charts in MVC.
I have a chart displaying values in a StackedColumn100 SeriesChartType with the corresponding y-axis values on the primary y-axis on the left side.
Since it is a 100% stacked column series, the primary y-axis is scaled from 0 to 100.
I have then added a secondary series in the form of a Line SeriesChartType tied to a secondary axis (on the right side). I would like this axis to adjust its scale based on the values in the series but it doesn't. No matter what the highest value of this series is, the secondary y-axis also has a scale between 0 to 100.
If I manually set the maximum value for the secondary y-axis the following way:
chart.ChartAreas[0].AxisY2.Maximum = 20;. It works but I don't want to do that since the maximum value can differ greatly based on the search criteria used.
I have really tried to find a solution for this but I can't. According to the documentation and samples it seems that the scale should be based on the series values but I don't get it to work that way. Any help would be greatly appreciated!
Below is a stand alone test function that recreates the problem. I call the function from my view with the following line:
<p><img src="#Url.Action("CreateChart_TestSecondaryAxis")" /> </p>
public FileResult CreateChart_TestSecondaryAxis()
{
System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart();
chart.Width = 800;
chart.Height = 400;
chart.BackColor = Color.FromArgb(211, 223, 240);
chart.BorderlineDashStyle = ChartDashStyle.Solid;
chart.BackSecondaryColor = Color.White;
chart.BackGradientStyle = GradientStyle.TopBottom;
chart.BorderlineWidth = 1;
chart.Palette = ChartColorPalette.BrightPastel;
chart.BorderlineColor = Color.FromArgb(26, 59, 105);
chart.RenderType = RenderType.BinaryStreaming;
chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
chart.AntiAliasing = AntiAliasingStyles.All;
chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal;
ChartArea chartArea = new ChartArea();
chartArea.Name = "TestSecondaryAxis";
chartArea.BackColor = Color.Transparent;
chartArea.AxisX.IsLabelAutoFit = false;
chartArea.AxisY.IsLabelAutoFit = false;
chartArea.AxisX.LabelStyle.Font =
new Font("Verdana,Arial,Helvetica,sans-serif",
8F, FontStyle.Regular);
chartArea.AxisY.LabelStyle.Font =
new Font("Verdana,Arial,Helvetica,sans-serif",
8F, FontStyle.Regular);
chartArea.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
chartArea.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);
chartArea.AxisY.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
chartArea.AxisX.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
chartArea.AxisX.Title = "Airport";
chartArea.AxisY.Title = "LandingConf";
chartArea.AxisY.TextOrientation = TextOrientation.Rotated270;
chartArea.AxisX.LabelStyle.IsEndLabelVisible = true;
chart.ChartAreas.Add(chartArea);
Series seriesPrimaryAxisConf3 = new Series();
seriesPrimaryAxisConf3.Name = "Conf 3";
seriesPrimaryAxisConf3.IsValueShownAsLabel = false;
seriesPrimaryAxisConf3.Color = Color.Blue;
seriesPrimaryAxisConf3.ChartType = SeriesChartType.StackedColumn100;
seriesPrimaryAxisConf3.BorderWidth = 2;
seriesPrimaryAxisConf3.ChartArea = "TestSecondaryAxis";
DataPoint point;
for (int i = 1; i < 11; i++)
{
point = new DataPoint();
point.AxisLabel = "Airport" + i.ToString();
point.YValues = new double[] { i };
seriesPrimaryAxisConf3.Points.Add(point);
}
chart.Series.Add(seriesPrimaryAxisConf3);
Series seriesPrimaryAxisConfFull = new Series();
seriesPrimaryAxisConfFull.Name = "Conf Full";
seriesPrimaryAxisConfFull.IsValueShownAsLabel = false;
seriesPrimaryAxisConfFull.Color = Color.Red;
seriesPrimaryAxisConfFull.ChartType = SeriesChartType.StackedColumn100;
seriesPrimaryAxisConfFull.BorderWidth = 2;
seriesPrimaryAxisConfFull.ChartArea = "TestSecondaryAxis";
for (int i = 1; i < 11; i++)
{
point = new DataPoint();
point.AxisLabel = "Airport" + i.ToString();
point.YValues = new double[] { 11-i };
seriesPrimaryAxisConfFull.Points.Add(point);
}
chart.Series.Add(seriesPrimaryAxisConfFull);
Series seriesSecondaryAxisNoOfFlights = new Series();
seriesSecondaryAxisNoOfFlights.Name = "NoOfFLights";
seriesSecondaryAxisNoOfFlights.IsValueShownAsLabel = false;
seriesSecondaryAxisNoOfFlights.Color = Color.Red;
seriesSecondaryAxisNoOfFlights.ChartType = SeriesChartType.Line;
seriesSecondaryAxisNoOfFlights.BorderWidth = 2;
seriesSecondaryAxisNoOfFlights.ChartArea = "TestSecondaryAxis";
for (int i = 1; i < 11; i++)
{
point = new DataPoint();
point.AxisLabel = "Airport" + i.ToString();
point.YValues = new double[] { i };
seriesSecondaryAxisNoOfFlights.Points.Add(point);
}
chart.Series.Add(seriesSecondaryAxisNoOfFlights);
chart.Series["NoOfFLights"].YAxisType = AxisType.Secondary;
chart.ChartAreas["TestSecondaryAxis"].AxisY2.LineColor = Color.Transparent;
chart.ChartAreas["TestSecondaryAxis"].AxisY2.MajorGrid.Enabled = false;
chart.ChartAreas["TestSecondaryAxis"].AxisY2.MajorTickMark.Enabled = false;
MemoryStream ms = new MemoryStream();
chart.SaveImage(ms);
return File(ms.GetBuffer(), #"image/png");
}
MSChart is a nice control but unfortunately Microsoft has always failed to properly document it.
And with the latest changes at MSDN things have gone from bad to worse, so I can't actually point to the rules that go for the various ChartTypes.
In your case I deduct this (rather wacky) rule:
To attach a non 100%-series to an indepently scaled secondary y-axis
it must be the first series but the stacked series still must be added
first.
So, if you want to get a result like this:
..you need to adapt the code. Here are the changes and additions needed..:
First we have to insert the line series at the front but do that after the stack100 series have beeen added..:
chart.Series.Insert(0, seriesSecondaryAxisNoOfFlights); // instead of adding it
Next we need to owner-draw the line as it would get burried under the columns otherwise.
Code the PostPaint event like this:
private void Chart_PostPaint(object sender, ChartPaintEventArgs e)
{
Chart chart = sender as Chart; //*
Series s = chart.Series[0]; // make sure to pick the right one!
Axis ax = chart.ChartAreas[0].AxisX;
Axis ay = chart.ChartAreas[0].AxisY2; // !!
var pts = s.Points.Select(x =>
new PointF((float)ax.ValueToPixelPosition(x.XValue),
(float)ay.ValueToPixelPosition(x.YValues[0])));
using (Pen pen = new Pen(s.Color, s.BorderWidth))
e.ChartGraphics.Graphics.DrawLines(pen, pts.ToArray());
}
For this to work the series need valid x-values. So add this line:
point.XValue = i; // set both x and y-values!
I also added a few nudges to the axis positioning:
ChartArea ca = chart.ChartAreas["TestSecondaryAxis"];
ca.AxisY.Maximum = 100;
ca.AxisX.Minimum = 0.5;
ca.AxisX.IntervalOffset = 0.5;

C# Scaling Axes of chart

I have a problem with charts in my application. I want to use charts to display histograms of pictures. I want to add a gradient rectangle under chart with colors from black to R/G/B/White, so I draw it as Background Image of each chart. When values on AxisY ar greater then 1k everything is fine, but when those values have less then 4 digits there is a problem screen. Anyone know how to prevent extension of AxisX?
Init charts:
for(int i = 0; i < 3; i++)
{
ca = new ChartArea();
ca.AxisX.Interval = 1D;
ca.AxisX.IntervalOffsetType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Number;
ca.AxisX.LabelAutoFitStyle = System.Windows.Forms.DataVisualization.Charting.LabelAutoFitStyles.WordWrap;
ca.AxisX.MajorGrid.Enabled = false;
ca.AxisY.MajorGrid.LineColor = System.Drawing.Color.DarkGray;
ca.BackColor = System.Drawing.Color.Transparent;
ca.BackSecondaryColor = System.Drawing.Color.Transparent;
ca.BorderWidth = 0;
ca.Name = "ChartArea" + i.ToString();
ca.AxisY.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont;
ca.AxisX.Minimum = 0;
ca.AxisX.Interval = 256;
ca.AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;
s = new Series();
s.BorderWidth = 0;
s.ChartArea = "ChartArea" + i.ToString();
s.IsVisibleInLegend = false;
s.Name = "Series" + i.ToString(); ;
s.Color = Colors[i];
s["PointWidth"] = "1";
HistCharts[i] = new Chart();
HistCharts[i].Anchor = AnchorStyles.Top | AnchorStyles.Right;
HistCharts[i].BackColor = Color.Transparent;
HistCharts[i].BackgroundImageLayout = ImageLayout.None;
HistCharts[i].BorderlineWidth = 0;
HistCharts[i].ChartAreas.Add(ca);
HistCharts[i].Location = new System.Drawing.Point(405, (i + 3) * Form.Height / 6 - 28);
HistCharts[i].Name = "Chart" + i.ToString();
HistCharts[i].Series.Add(s);
HistCharts[i].Size = new System.Drawing.Size(297, Form.Height / 6 - 27);
HistCharts[i].TabIndex = 6;
HistCharts[i].Text = "chart" + i.ToString();
HistCharts[i].Visible = false;
HistCharts[i].SendToBack();
}
SetChartImage();
for(int i = 0; i < 3; i++)
HistCharts[i].BackgroundImage = HistImages[i];
Set new series and paint:
if(Hists == null)
{
HistCharts[0].Visible = false;
HistCharts[1].Visible = false;
HistCharts[2].Visible = false;
UpdateStatTimer(Time);
return;
}
HistCharts[0].BackgroundImage = HistImages[Hists.Length > 1 ? 1 : 0];
if(Hists[0].SequenceEqual(Hists[1]) && Hists[0].SequenceEqual(Hists[2]))
{
HistCharts[0].Series[0].Color = Color.Black;
HistCharts[0].BackgroundImage = HistImages[0];
HistCharts[0].Visible = true;
HistCharts[1].Visible = false;
HistCharts[2].Visible = false;
}
else
{
HistCharts[0].Series[0].Color = Color.Red;
HistCharts[0].BackgroundImage = HistImages[1];
HistCharts[0].Visible = true;
HistCharts[1].Visible = true;
HistCharts[2].Visible = true;
}
int Max = 0;
for(int i = 0; i < 3; i++)
{
HistCharts[i].Series[0].Points.Clear();
HistCharts[i].ChartAreas[0].AxisY.Maximum = Double.NaN;
for(int j = 0; j < Hists[i].Length; j++)
HistCharts[i].Series[0].Points.AddXY(j + 0.5, Hists[i][j]);
HistCharts[i].Update();
if(HistCharts[i].ChartAreas[0].AxisY.Maximum > Max)
Max = (int) HistCharts[i].ChartAreas[0].AxisY.Maximum;
}
if(StatisticsItemCheck.Checked == false)
{
for(int i = 0; i < 3; i++)
HistCharts[i].ChartAreas[0].AxisY.Maximum = Max;
}
if all Hists are equal Green and Blue histograms are invisible and Red Histogram becomes GrayScale Histogram
This is not really about scaling..:
The reason your images don't always align with the Y-Axis is that the Y-Axis legend takes more or less room in various cases. This make the inner plot area move to the right and your carefully aligned image doesn't fit anymore.
When the Y-Axis moves to the right the whole plotarea shrinks, at least if the default vlaues of Auto are still valid for the various elements..
The simplest workaround is to set the position from Auto to a fixed value that suits all your data:
chart1.ChartAreas[0].InnerPlotPosition.X = someValue;
Note that all element position values are in percent of the whole chart! So maybe you will want to modify it upon resizing the chart..? As you have noticed, you also have to resize you images..
To find a good value you can use the debugger to see which are the current ones in both of your cases and pick the larger one and then some extra for safety..
In the same veign you may want to get better control over the format, i.e. the number of digits on your y-axis label values, maybe like this..:
chart1.ChartAreas[0].AxisY.LabelStyle.Format = "0.00"; // some formatstring
Update:
To make use of the system's AutoScaling during(after a resize, you can use this workaround:
First set the Auto on and copy the resulting Elementposition. Then use those values to create a new one under control:
int LeftEdge = yourValue;
chart1.ChartAreas[0].InnerPlotPosition.Auto = true;
ElementPosition EP = chart1.ChartAreas[0].InnerPlotPosition;
chart1.ChartAreas[0].InnerPlotPosition =
new ElementPosition(LeftEdge, EP.Y, EP.Height, 100 - LeftEdge);

Zedgraph Horizontal Bar graph with different bar colors C#

I am working on zedgraph and generating a horizontal bar graph. I only want to know if there is any way by which each single bar can be made of different color. The output of the code is acceptable, I only intend on changing the color of the bars being generated. Any help would be much appreciated. Thanks!
myPane.YAxis.Title.Text = "Nominees";
myPane.XAxis.Title.Text = "Votes";
// Make up some random data points
string[] labels= new string[count];
for (int i = count-1; i >= 0; i--)
{
labels[counter] = voternames[i];
counter++;
}
for (int i = count1-1; i >= 0; i--)
{
y0[counter1] = Convert.ToDouble(votes[i]);
counter1++;
}
// Generate a red bar with "Curve 1" in the legend
BarItem myBar = myPane.AddBar("", y0, null, Color.Green);
// Draw the X tics between the labels instead of
// at the labels
myPane.YAxis.MajorTic.IsBetweenLabels = false;
// Set the XAxis labels
myPane.YAxis.Scale.TextLabels = labels;
// Set the XAxis to Text type
myPane.YAxis.Type = AxisType.Text;
myPane.BarSettings.Base = BarBase.Y;
// Fill the Axis and Pane backgrounds
myPane.Fill = new Fill(Color.FromArgb(250, 250, 255));
// Tell ZedGraph to refigure the
// axes since the data have changed
zgc.AxisChange();
zgc.Refresh();
Found what I was looking for, the original link to source is:
http://www.ironpython.info/index.php?title=Multi-colored_Bar_Chart_with_ZedGraph. The main modification was making a Point pair list instead of sending the double array for creating bars, giving reference to color array and setting min and max range for fills. The modified code is as follows:
myPane.YAxis.Title.Text = "Nominees";
myPane.XAxis.Title.Text = "Votes";
// Make up some random data points
string[] labels= new string[count];
//string[] labelx = new string[count];
for (int i = count-1; i >= 0; i--)
{
labels[counter] = voternames[i];
counter++;
}
for (int i = count1-1; i >= 0; i--)
{
y0[counter1] = Convert.ToDouble(votes[i]);
counter1++;
}
for (int i = 0; i < y0.Length; i++)
{
//Adding the x axis data and using y axis as a source to color a single bar
list.Add(y0[i], i / 2.0);
}
Color[] colors = new Color[] {Color.Red, Color.Yellow, Color.Green, Color.Blue, Color.Purple};
// Generate a bar with point pair list in the legend
BarItem myBar = myPane.AddBar("", list, Color.Green);
// Giving ref of color array
myBar.Bar.Fill = new Fill(colors);
//Setting to fill with using point values of y axis
myBar.Bar.Fill.Type = FillType.GradientByY;
//Setting min and max range is important
myBar.Bar.Fill.RangeMin = 0;
myBar.Bar.Fill.RangeMax = Convert.ToInt32(y0[0]);
// Draw the X tics between the labels instead of
// at the labels
myPane.YAxis.MajorTic.IsBetweenLabels = false;
// Set the XAxis labels
myPane.YAxis.Scale.TextLabels = labels;
// Set the XAxis to Text type
myPane.YAxis.Type = AxisType.Text;
myPane.BarSettings.Base = BarBase.Y;
// Fill the Axis and Pane backgrounds
//myPane.Chart.Fill = new Fill(Color.White,Color.FromArgb(255, 255, 166), 90F);
myPane.Fill = new Fill(Color.FromArgb(250, 250, 255));
// Tell ZedGraph to refigure the
// axes since the data have changed
zgc.AxisChange();
zgc.Refresh();

MS Chart Strip Lines Intraday

I use a line chart with double in Y axis and DateTime in X axis. My plot has only intraday data: I have one point each minutes between 8 am and 10 pm.
I want to underline certain periods of the plot. The first period begins at 8:50 and continues during 20 minutes. For this I use a stripLine with the following code:
var stripLine = new StripLine();
stripLine.BackColor = Color.White;
stripLine.BackGradientStyle = GradientStyle.TopBottom;
stripLine.BackImageTransparentColor = Color.White;
stripLine.BackSecondaryColor = Color.Transparent;
stripLine.Interval = 1;
stripLine.IntervalType = DateTimeIntervalType.Days;
stripLine.IntervalOffset = 50;
stripLine.IntervalOffsetType = DateTimeIntervalType.Minutes;
stripLine.StripWidth = 20;
stripLine.StripWidthType= DateTimeIntervalType.Minutes;
chartArea.AxisX.StripLines.Add(stripLine);
However I do not get the right result. Indeed, all my chart area is underlined by the strip line..
Here is a plot to illustrate what I want to achieve:
Your question is a bit obscure: your code is striplining the area vertically from 8:50 to 9:10 A.M.
Do you want to create Stripline every (x):50 to (x+1):10 ?
for(int i=0;i<24;i++)
{
var stripLine = new StripLine();
stripLine.BackColor = Color.White;
stripLine.BackGradientStyle = GradientStyle.TopBottom;
stripLine.BackImageTransparentColor = Color.White;
stripLine.BackSecondaryColor = Color.Transparent;
stripLine.Interval = (double)i;
stripLine.IntervalType = DateTimeIntervalType.Hours;
stripLine.IntervalOffset = 50;
stripLine.IntervalOffsetType = DateTimeIntervalType.Minutes;
stripLine.StripWidth = 20;
stripLine.StripWidthType = DateTimeIntervalType.Minutes;
Chart1.ChartAreas[0].AxisX.StripLines.Add(stripLine);
}
Should work.
Do you want to show the StripLine exactly at the points you showed?
var stripLine = new StripLine();
stripLine.BackColor = Color.White;
stripLine.BackGradientStyle = GradientStyle.TopBottom;
stripLine.BackImageTransparentColor = Color.White;
stripLine.BackSecondaryColor = Color.Transparent;
stripLine.Interval = 9;
stripLine.IntervalType = DateTimeIntervalType.Hours;
stripLine.IntervalOffset = 28;
stripLine.IntervalOffsetType = DateTimeIntervalType.Minutes;
stripLine.StripWidth = 8;
stripLine.StripWidthType= DateTimeIntervalType.Seconds;
chartArea.AxisX.StripLines.Add(stripLine);
Is the right solution.
A StripLine is a line and it will only allow you the add colored rectangles.
To create an area that follows your spline curve you need to either
draw it in the PostPaint event
or use an extra Series of type SplineArea
Here is the 2nd way:
..
Series s3 = chart.Series.Add("S3 ");
s1.ChartType = SeriesChartType.Spline;
s2.ChartType = SeriesChartType.Line;
s3.ChartType = SeriesChartType.SplineArea;
s2.Color = Color.Red;
s3.Color = Color.FromArgb(55, Color.RosyBrown);
for (int i = 0; i < 50; i++)
{
s1.Points.AddXY(i,20 - rnd.Next(10) );
s2.Points.AddXY(i,17);
if (i > 10 && i < 20) s3.Points.AddXY(i, s1.Points[i].YValues[0]);
}

Categories

Resources