Change the format of the axis tick labels in LiveCharts - c#

I just can't find a solution for changing the format of the y-axis tick labels.
Now I get labels like 0.03 and 0.035. But I always need three digits behind the decimal point.
The big question is, how to access the label format?
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using LiveCharts;
using LiveCharts.Helpers;
using LiveCharts.Wpf;
using LiveCharts.Wpf.Charts.Base;
using Brushes = System.Windows.Media.Brushes;
using Color = System.Windows.Media.Color;
using MessageBox = System.Windows.Forms.MessageBox;
namespace LiveAnalysis
{
public partial class Form1 : Form
{
List<DateTime> xvals = new List<DateTime>();
List<double> yvals = new List<double>();
private int _amountValues;
private int _startValue;
private List<double> _yvalsRange;
public Form1()
{
InitializeComponent();
// event
cartesianChart2.DataClick += CartesianChart1OnDataClick;
hScrollBar1.ValueChanged += (sender, e) => hScrollBar1_ValueChange(sender, e, hScrollBar1.Value);
// get original data
using (var db = new Analysis.DataClasses1DataContext())
{
var lttResults = db.LttResults;
var par1 = 0.0;
foreach (var data in lttResults)
{
if (data.GatewayEventType == 41)
par1 = data.FloatValue;
if (data.GatewayEventType != 42) continue;
var par2 = data.FloatValue;
var diff = Math.Round(par1 - par2, 3);
yvals.Add(diff);
xvals.Add(data.DateTime);
}
}
// chart settings
ChartSettings();
}
private void ChartSettings()
{
// performance
cartesianChart2.DisableAnimations = true;
cartesianChart2.DataTooltip = null;
cartesianChart2.Hoverable = false;
_startValue = 0;
_amountValues = 400;
_yvalsRange = yvals.GetRange(_startValue, _startValue + _amountValues);
// series setting
ScatterSeries scatterSeries1 = new ScatterSeries("Series1");
cartesianChart2.Series.Add(scatterSeries1);
scatterSeries1.Values = _yvalsRange.AsChartValues();
scatterSeries1.MaxPointShapeDiameter = 10;
scatterSeries1.Title = "Series1";
cartesianChart2.AxisX.Add(new Axis
{
Name = "xAxis",
Title = "DateTime",
FontSize = 22,
Foreground = System.Windows.Media.Brushes.Black,
MinValue = 0,
MaxValue = _amountValues,
});
cartesianChart2.AxisY.Add(new Axis
{
Name = "yAxis",
Title = "Time difference",
FontSize = 22,
Foreground = System.Windows.Media.Brushes.Black,
MinValue = -0.025,
MaxValue = 0.04,
});
}
private void CartesianChart1OnDataClick(object sender, ChartPoint chartPoint)
{
label1.Text = $#"You clicked: {chartPoint.X},{chartPoint.Y}";
}
private void button2_Click_1(object sender, EventArgs e)
{
}
private void hScrollBar1_ValueChange(object sender, EventArgs e, int value)
{
RedrawGraph(value);
}
private void RedrawGraph(int value)
{
_startValue = value * 10;
_yvalsRange = yvals.GetRange(_startValue, _startValue + _amountValues);
cartesianChart2.Series[0].Values = _yvalsRange.AsChartValues();
cartesianChart2.AxisX[0].MinValue = _startValue;
cartesianChart2.AxisX[0].MaxValue = _startValue + _amountValues;
}
}
}

The answer is:
Func<double, string> formatFunc = (x) => string.Format("{0:0.000}", x);
cartesianChart2.AxisY.Add(new Axis
{
LabelFormatter = formatFunc,
});

Related

How can I display an image embedded in my program using the value from a random number generator?

I'm trying to build a Russian Roulette style program where you click a button and it randomly selects one of 25 images to display on screen but I can't seem to figure out how to call the images using the generator.
It works fine when I select an image manually, as seen in my code below, but anything else seems to return an error.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label_click(object sender, EventArgs e)
{
Close();
}
int mouseX = 0, mouseY = 0;
bool mouseDown;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
private void GOBUTN_Paint(object sender, PaintEventArgs e)
{
}
//Sharing is caring: Communism goes here
private System.Windows.Forms.Timer timtim;
int rand0;
PictureBox Rooskie = new PictureBox();
Label test = new Label();
Random rando = new Random();
List<int> duplicheck = new List<int>();
private void boopthesnoot(object sender, EventArgs e)
{
dingding:
//Hell yeah, random numbers here
rand0 = rando.Next(1, 26);
/*string combowombo = string.Join(", ", duplicheck.ToArray());
test.Text = combowombo;
test.Font = new Font("Calibri", 20);
Controls.Add(test);
test.Location = new Point(0, 200);
test.Height = 1000;
test.Width = 1000;*/
if(duplicheck.Contains(rand0))
{
goto dingding;
}
else
{
GOBUTTON.Hide();
pictureBox1.Hide();
pictureBox2.Hide();
//Fuckin image code goes here my dood
Rooskie.Width = 1160;
Rooskie.Height = 620;
Bitmap image = new Bitmap(WindowsFormsApp1.Properties.Resources._1);
Rooskie.Dock = DockStyle.Fill;
Rooskie.Image = (Image)image;
Controls.Add(Rooskie);
Rooskie.SizeMode = PictureBoxSizeMode.CenterImage;
//Aww shit, it's that timer time
timtim = new System.Windows.Forms.Timer();
timtim.Tick += new EventHandler(clockfinish);
timtim.Interval = 3000;
timtim.Start();
duplicheck.Add(rand0);
if (duplicheck.Count == 25)
{
duplicheck = new List<int>();
}
}
}
private void clockfinish(object sender, EventArgs e)
{
//CEASE THE TIMER AND GIVE ME BACK MY BUTTON
Rooskie.Image = null;
timtim.Stop();
GOBUTTON.Show();
pictureBox1.Show();
pictureBox2.Show();
}
The expected result is when the user presses the button it calls up the image without having to load it from a folder.

Error creating a line graph on winform

I keep getting this error when trying to initialise the form with my graph on it. Can't figure out a work around for it. Think it has something to do with Data Binding
Any ideas ?
Here is my code -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace NoCAnalysisTool2
{
public partial class Visualisation : UserControl
{
public string tx_graph { get; set; }
public List<int> tx_graphData { get; set; }
public Visualisation(string txGraph, List<int> tx_GData)
{
InitializeComponent();
tx_graph = txGraph;
tx_graphData = tx_GData;
// Set 3D chart settings
chart1.ChartAreas["Default"].Area3DStyle.Enable3D = true;
chart1.ChartAreas["Default"].Area3DStyle.IsRightAngleAxes = false;
chart1.ChartAreas["Default"].Area3DStyle.Inclination = 40;
chart1.ChartAreas["Default"].Area3DStyle.Rotation = 20;
chart1.ChartAreas["Default"].Area3DStyle.LightStyle = LightStyle.Realistic;
// Populate series with random data
Random random = new Random();
for (int pointIndex = 0; pointIndex < 10; pointIndex++)
{
chart1.Series["Series1"].Points.AddY(random.Next(45, 95));
chart1.Series["Series2"].Points.AddY(random.Next(5, 75));
}
// Set series chart type
chart1.Series["Series1"].ChartType = SeriesChartType.Line;
chart1.Series["Series2"].ChartType = SeriesChartType.Spline;
// Set point labels
chart1.Series["Series1"].IsValueShownAsLabel = true;
chart1.Series["Series2"].IsValueShownAsLabel = true;
// Enable X axis margin
chart1.ChartAreas["Default"].AxisX.IsMarginVisible = true;
// Enable the ShowMarkerLines
chart1.Series["Series1"]["ShowMarkerLines"] = "true";
chart1.Series["Series2"]["ShowMarkerLines"] = "true";
}
private void TxGraph_Load(object sender, EventArgs e)
{
}
private void Tx_graph_Click(object sender, EventArgs e)
{
}
private void Visualisation_Load(object sender, EventArgs e)
{
}
private void chart11_Click(object sender, EventArgs e)
{
}
}
}
The 'default' ChartArea is not called "Default" but "ChartArea1".
Trying to access an indexer by a wrong name results in an Argument Exeption.
You have the choice of either calling it by its index:
ChartArea ca = chart1.ChartAreas[0];
Or by its right name:
ChartArea ca = chart1.ChartAreas["ChartArea1"];
Or set the Name property th a string you like..:
chart1.ChartAreas[0].Name = "Default";
..and then calli it by that Name:
chart1.ChartAreas["Default"].Area3DStyle.Enable3D = true;
Btw: I hope you have added the 2nd Series in the designer and given it the right Name ;-)

How can I delete all Panels from my calendar?

I'm programming an calendar with C# right now.
If i call my calendar, it creates as much panels as the current month has days. But if I want to increase the current month by one, the panels from the current month are stilt there.
So i have to delete all my panels as soon as I change the month.
But how can i do it in this case ?
Thanks for the help.
Code eplain:
First I call the createPanel method, to create panels for the current month.
Next if I click the MonthAdd method, I want to delete all my created panels.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;
namespace Einteilungs_Plan
{
public partial class Kalender : Form
{
public DateTime TodayDate { get; set; }
int counting = 0;
public Kalender()
{
InitializeComponent();
//Kalenderwochen initialisieren
monat(counting);
createPanel(true);
}
public string monat(int adding)
{
string monat = DateTime.Now.AddMonths(adding).ToString("MMMM");
tbMonat.Text = monat;
return monat;
}
private void btnAddMonth_Click(object sender, EventArgs e)
{
counting++;
if(counting < 12)
{
monat(counting);
switch (counting)
{
case 0:
int number = 10;
break;
case 1:
break;
default:
break;
}
}
else
{
counting--;
}
}
private void btnRemoveMonth_Click(object sender, EventArgs e)
{
counting--;
if (counting > -1)
{
monat(counting);
}
else
{
counting++;
}
}
public void createPanel(bool remove)
{
var numDays = DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month);
int locationX = 12;
int locationY = 74;
for (int i = 0; i <= numDays; i++)
{
//Create Panel
Panel test = new Panel();
//Fill Panel
test.Name = "panel" + i;
test.Width = 200;
test.Height = 100;
test.BackColor = Color.White;
test.Location = new System.Drawing.Point(locationX, locationY);
this.Controls.Add(test);
test.Show();
if(i == 6 || i == 13 || i == 20 || i == 28)
{
locationY += 106;
locationX = -194;
}
locationX += 206;
}
}
public void Kalender_Shown(object sender, EventArgs e)
{
}
private void Kalender_Load(object sender, EventArgs e)
{
}
private void btnNeuerEintrag_Click(object sender, EventArgs e)
{
Formular formular = new Formular();
formular.Show();
formular.Focus();
}
private void btnHinzufügen_Click(object sender, EventArgs e)
{
Formular formular = new Formular();
formular.Show();
formular.Focus();
}
}
}
...
for (int i = 0; i <= numDays; i++)
{
//Create Panel
test[i] = new Panel();
}
...
and then
this.Control.Remove(test[i]);
I'm not sure if I undestood you well but first simple solutiona that comes into my mind is that while creating panels you can keep them in some List for example and before generating new month you can call
foreach (var p in panels)
this.Controls.Remove(p);

How do I display a shaded area in a Winform .Net 4.0 Chart Rangebar (C#)

I am displaying a Winform .Net Chart rangebar graph showing tickets worked on during the day for an employee. I would like the shade the area from 08:00 to 17:00 light green if I could. I tried to put a range series on, but it won't allow that. I think I could use the postpaint method to do it, but I can't figure out how to find the positions to draw a rectangle.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Data.Objects;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Windows.Forms.DataVisualization.Charting;
namespace CWHelper
{
public partial class DailyTimeEntryDisplay : CWHelper.BaseForm
{
Object dataLock = new object();
public DailyTimeEntryDisplay(string member_ID)
{
InitializeComponent();
mMember_ID = member_ID;
}
string mMember_ID;
private void DailyTimeEntryDisplay_Load(object sender, EventArgs e)
{
DateTime minDate = new DateTime(1900, 1, 1);
chart1.ChartAreas[0].AxisY.Minimum = minDate.ToOADate();
chart1.ChartAreas[0].AxisY.Maximum = minDate.AddDays(1).ToOADate();
chart1.ChartAreas[0].AxisY.Interval = 1;
chart1.ChartAreas[0].AxisY.LabelStyle.Format = "HH:mm";
chart1.ChartAreas[0].AxisY.LabelStyle.Interval = 1;
chart1.ChartAreas[0].AxisY.LabelStyle.Angle = 45;
chart1.ChartAreas[0].AxisY.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.LabelStyle.Interval = 1;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.RangeBar;
chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.String;
chart1.Series[0].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
double rangeStart = new DateTime(1900,1,1,8,0,0).ToOADate();
double rangeEnd = new DateTime(1900,1,1,17,0,0).ToOADate();
double[] range = new double[] {rangeStart,rangeEnd};
DisplayData();
}
private void DisplayData()
{
try
{
DateTime sd = dateTimePicker1.Value;
DateTime? dt = new DateTime(sd.Year, sd.Month, sd.Day);
cwwebapp_drsEntities dc = new cwwebapp_drsEntities();
var q = dc.GetTimeEntry(mMember_ID, dt);
var ql = q.ToList();
var chartData = (from x in ql
select new { SR_Service_RecID = x.SR_Service_RecID != 0 ? x.SR_Service_RecID.ToString() : "Time Entry:",
Time_Start = x.Time_Start.ToOADate(),
Time_End = x.Time_End.ToOADate(),
tooltip = x.Company_Name + " : " + x.Notes,
summary = x.Summary
}).ToList();
chart1.Series[0].Points.DataBind(chartData, "SR_Service_RecID", "Time_Start,Time_End", "Tooltip=tooltip,Label=summary");
}
catch (Exception ex)
{
Debug.Print(ex.Message);
if (ex.InnerException != null)
{
Debug.Print(ex.InnerException.Message);
}
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DisplayData();
}
private void LeftButton_Click(object sender, EventArgs e)
{
dateTimePicker1.Value = dateTimePicker1.Value.AddDays(-1);
}
private void RightButton_Click(object sender, EventArgs e)
{
dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1);
}
private void ReloadButton_Click(object sender, EventArgs e)
{
DisplayData();
}
}
}
IMO, you don't need any PostPaint method. .Net Charting allows you to do that. Please try the following code:
private void DailyTimeEntryDisplay_Load(object sender, EventArgs e)
{
chart1.Palette = ChartColorPalette.None;
chart1.PaletteCustomColors = new Color[] { Color.LightGreen };
//DateTime minDate = new DateTime(1900, 1, 1);
//chart1.ChartAreas[0].AxisY.Minimum = minDate.ToOADate();
//chart1.ChartAreas[0].AxisY.Maximum = minDate.AddDays(1).ToOADate();
chart1.ChartAreas[0].AxisY.Interval = 1;
chart1.ChartAreas[0].AxisY.LabelStyle.Format = "HH:mm";
chart1.ChartAreas[0].AxisY.LabelStyle.Interval = 1;
chart1.ChartAreas[0].AxisY.LabelStyle.Angle = 45;
chart1.ChartAreas[0].AxisY.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.LabelStyle.Interval = 1;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Auto;
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.RangeColumn; // "RangeColumn" instead of "RangeBar"
chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.String;
chart1.Series[0].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Time; // "Time" instead of "DateTime"
DisplayData();
}

Chart creating dynamically. in .net, c#

Does anybody have some experience working with charts in .NET? Specially I want to create them programmatically.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
Chart mych = new Chart();
mych.Series.Add("duck");
mych.Series["duck"].SetDefault(true);
mych.Series["duck"].Enabled = true;
mych.Visible = true;
for (int q = 0; q < 10; q++)
{
int first = rnd.Next(0,10);
int second = rnd.Next(0,10);
mych.Series["duck"].Points.AddXY(first, second);
Debug.WriteLine(first + " " + second);
}
mych.Show();
Controls.Add(mych);
mych.Show();
}
}
}
I'm trying to use .NET (.net 4, Visual Studio 2010) chart, but the random generated data set, doesn't appear. The chart remained blank. I searched for examples and only found ones like this , and, yes with manual "drag" method it works. I have no idea why the data I programmatically generate doesn't appear.
Yep.
// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart). Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//
using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Dino.Tools.WebMonitor
{
public class FakeChartForm1 : Form
{
private System.ComponentModel.IContainer components = null;
System.Windows.Forms.DataVisualization.Charting.Chart chart1;
public FakeChartForm1 ()
{
InitializeComponent();
}
private double f(int i)
{
var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
return f1;
}
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = "Series1",
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Line
};
this.chart1.Series.Add(series1);
for (int i=0; i < 100; i++)
{
series1.Points.AddXY(i, f(i));
}
chart1.Invalidate();
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
this.SuspendLayout();
//
// chart1
//
chartArea1.Name = "ChartArea1";
this.chart1.ChartAreas.Add(chartArea1);
this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
legend1.Name = "Legend1";
this.chart1.Legends.Add(legend1);
this.chart1.Location = new System.Drawing.Point(0, 50);
this.chart1.Name = "chart1";
// this.chart1.Size = new System.Drawing.Size(284, 212);
this.chart1.TabIndex = 0;
this.chart1.Text = "chart1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.chart1);
this.Name = "Form1";
this.Text = "FakeChart";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
this.ResumeLayout(false);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FakeChartForm1());
}
}
}
UI:
Microsoft has a nice chart control. Download it here. Great video on this here. Example code is here. Happy coding!
Add a reference to System.Windows.Form.DataVisualization, then add the appropriate using statement:
using System.Windows.Forms.DataVisualization.Charting;
private void CreateChart()
{
var series = new Series("Finance");
// Frist parameter is X-Axis and Second is Collection of Y- Axis
series.Points.DataBindXY(new[] { 2001, 2002, 2003, 2004 }, new[] { 100, 200, 90, 150 });
chart1.Series.Add(series);
}
Try to include these lines on your code, after mych.Visible = true;:
ChartArea chA = new ChartArea();
mych.ChartAreas.Add(chA);
You need to attach the Form1_Load handler to the Load event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
Chart mych = new Chart();
mych.Height = 100;
mych.Width = 100;
mych.BackColor = SystemColors.Highlight;
mych.Series.Add("duck");
mych.Series["duck"].SetDefault(true);
mych.Series["duck"].Enabled = true;
mych.Visible = true;
for (int q = 0; q < 10; q++)
{
int first = rnd.Next(0, 10);
int second = rnd.Next(0, 10);
mych.Series["duck"].Points.AddXY(first, second);
Debug.WriteLine(first + " " + second);
}
Controls.Add(mych);
}
}
}

Categories

Resources