public BasicLine() { InitializeComponent(); //we create a new SeriesCollection Series = new SeriesCollection(); //create some LineSeries var charlesSeries = new LineSeries { Title = "Charles", Values = new ChartValues<double> {10, 5, 7, 5, 7, 8} }; var jamesSeries = new LineSeries { Title = "James", Values = new ChartValues<double> { 5, 6, 9, 10, 11, 9 } }; //add our series to our SeriesCollection Series.Add(charlesSeries); Series.Add(jamesSeries); //that's it, LiveCharts is ready and listening for your data changes. DataContext = this; }
public static void ComboHorizontal(dotnetCHARTING.Chart chart, int width, int height, string title, DataTable table, string xColumn, string yColumn) { SeriesCollection SC = new SeriesCollection(); Series s = new Series(); foreach (DataRow row in table.Rows) { string telType = row[xColumn].ToString(); Element e = new Element(); e.Name = telType; e.LabelTemplate = "%PercentOfTotal"; e.YValue = Convert.ToDouble(row[yColumn].ToString()); s.Elements.Add(e); } SC.Add(s); chart.TempDirectory = "temp"; chart.Use3D = false; chart.DefaultAxis.Interval = 10; chart.DefaultAxis.CultureName = "zh-CN"; chart.Palette = new Color[] { Color.FromArgb(49, 255, 49), Color.FromArgb(255, 255, 0), Color.FromArgb(255, 99, 49), Color.FromArgb(0, 156, 255) }; chart.DefaultElement.SmartLabel.AutoWrap = true; chart.Type = ChartType.ComboHorizontal; chart.Size = width + "x" + height; chart.DefaultElement.SmartLabel.Text = ""; chart.Title = title; chart.DefaultElement.ShowValue = true; chart.PieLabelMode = PieLabelMode.Outside; chart.ShadingEffectMode = ShadingEffectMode.Three; chart.NoDataLabel.Text = "û��������ʾ"; chart.SeriesCollection.Add(SC); }
public BasicStackedColumnExample() { InitializeComponent(); SeriesCollection = new SeriesCollection { new StackedColumnSeries { Values = new ChartValues<double> {4, 5, 6, 8}, StackMode = StackMode.Values, // this is not necessary, values is the default stack mode DataLabels = true }, new StackedColumnSeries { Values = new ChartValues<double> {2, 5, 6, 7}, StackMode = StackMode.Values, DataLabels = true } }; //adding series updates and animates the chart SeriesCollection.Add(new StackedColumnSeries { Values = new ChartValues<double> { 6, 2, 7 }, StackMode = StackMode.Values }); //adding values also updates and animates SeriesCollection[2].Values.Add(4d); Labels = new[] { "Chrome", "Mozilla", "Opera", "IE" }; Formatter = value => value + " Mill"; this.CleanSeparator = DefaultAxes.CleanSeparator; }
public ZoomingAndPanning() { InitializeComponent(); var gradientBrush = new LinearGradientBrush {StartPoint = new Point(0, 0), EndPoint = new Point(0, 1)}; gradientBrush.GradientStops.Add(new GradientStop(Color.FromRgb(33, 148, 241), 0)); gradientBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1)); SeriesCollection = new SeriesCollection { new LineSeries { Values = GetData(), Fill = gradientBrush, StrokeThickness = 1, PointGeometrySize = 0 } }; ZoomingMode = ZoomingOptions.X; XFormatter = val => new DateTime((long) val).ToString("dd MMM"); YFormatter = val => val.ToString("C"); DataContext = this; }
public RotatedBar() { InitializeComponent(); var config = new SeriesConfiguration<double>().X(value => value); SeriesCollection = new SeriesCollection(config) { new BarSeries { Title = "inverted series", Values = new double[] {10, 15, 18, 20, 15, 13}.AsChartValues(), DataLabels = true }, new BarSeries { Title = "inverted series 2", Values = new double[] {4, 8, 19, 19, 16, 12}.AsChartValues(), DataLabels = true }, new LineSeries { Title = "inverted line series", Values = new double[] {10, 15, 18, 20, 15, 13}.AsChartValues(), Fill = Brushes.Transparent } }; DataContext = this; }
public IrregularLine() { InitializeComponent(); //we create a configuration to map our values type, in this case System.Windows.Point var config = new SeriesConfiguration<Point>() .X(point => point.X) // we use point.X as the X of our chart (you don't say!) .Y(point => point.Y); // we use point.Y as the Y of our chart -.-" //we pass the config to the SeriesCollection constructor, or you can use Series.Setup(config) Series = new SeriesCollection(config) { new LineSeries { Values = new ChartValues<Point> { new Point(1, 10), new Point(2, 15), new Point(4, 29), new Point(8, 38), new Point(16, 45), new Point(32, 55), new Point(64, 62), new Point(128, 76), new Point(256, 95) }, Fill = Brushes.Transparent } }; DataContext = this; }
public LogarithmicAxis() { InitializeComponent(); //we create a configuration to map our values type, in this case System.Windows.Point var config = new SeriesConfiguration<Point>() .X(point => Math.Log(point.X, 10)) // we use log10(point.X) as X .Y(point => point.Y); // we use point.Y as the Y of our chart (amm.... yes, we are so f* smart!) //we pass the config to the SeriesCollection constructor, or you can use Series.Setup(config) Series = new SeriesCollection(config) { new LineSeries { Values = new ChartValues<Point> { new Point(1, 10), new Point(10, 15), new Point(100, 29), new Point(1000, 38), new Point(10000, 45), new Point(100000, 55) } } }; //to display labels we convert back from log //this is just the inverse operation XFormatter = x => { return Math.Pow(10, x).ToString(); }; DataContext = this; }
public SensorEnumerator(SeriesCollection collection) { foreach (Series s in collection) { dataEnums.Add(s.Points.GetEnumerator()); } }
public LogarithmScaleExample() { InitializeComponent(); SeriesCollection = new SeriesCollection(Mappers.Xy<ObservablePoint>() .X(point => Math.Log10(point.X)) .Y(point => point.Y)) { new LineSeries { Values = new ChartValues<ObservablePoint> { new ObservablePoint(1, 5), new ObservablePoint(10, 6), new ObservablePoint(100, 4), new ObservablePoint(1000, 2), new ObservablePoint(10000, 8), new ObservablePoint(100000, 2), new ObservablePoint(1000000, 9), new ObservablePoint(10000000, 8) } } }; Formatter = value => Math.Pow(10, value).ToString("N"); DataContext = this; }
public StackedColumnExample() { InitializeComponent(); SeriesCollection = new SeriesCollection { new StackedColumnSeries { Values = new ChartValues<ObservableValue> { new ObservableValue(5), new ObservableValue(8), new ObservableValue(2), new ObservableValue(4), new ObservableValue(6), new ObservableValue(2), new ObservableValue(9), new ObservableValue(3) }, DataLabels = true }, new StackedColumnSeries { Values = new ChartValues<ObservableValue> { new ObservableValue(7), new ObservableValue(4), new ObservableValue(1), new ObservableValue(7), new ObservableValue(2), new ObservableValue(7), new ObservableValue(0), new ObservableValue(3) }, DataLabels = true }, new StackedColumnSeries { Values = new ChartValues<ObservableValue> { new ObservableValue(6), new ObservableValue(2), new ObservableValue(8), new ObservableValue(2), new ObservableValue(9), new ObservableValue(2), new ObservableValue(3), new ObservableValue(3) }, DataLabels = true } }; Labels = new[] { "Jan", "Feb","Mar", "Apr", "May", "Jun", "Jul", "Ago" }; DataContext = this; }
public DynamicLine() { InitializeComponent(); //In this case we will not only plot double values //to make it easier to handle "live-data" we are going to use WeatherViewModel class //we need to let LiveCharts know how to use this model //first we create a new configuration for WeatherViewModel var config = new SeriesConfiguration<WeatherViewModel>(); //now we map X and Y //we will use Temperature as Y config.Y(model => model.Temperature); //and DateTime as X, we convert to OADate so we can plot it easly. config.X(model => model.DateTime.ToOADate()); //now we create our series with this configuration Series = new SeriesCollection(config) {new LineSeries {Values = new ChartValues<WeatherViewModel>()}}; //to display a custom label we will use a formatter, //formatters are just functions that take a double value as parameter //and return a string, in this case we will convert the OADate to DateTime //and then use a custom date format XFormatter = val => DateTime.FromOADate(val).ToString("hh:mm:ss tt"); //now for Y we are rounding and adding ° for degrees YFormatter = val => Math.Round(val) + " °"; //Don't forget DataContext so we can bind these properties. DataContext = this; _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; _timer.Tick += TimerOnTick; }
public BasicRowExample() { InitializeComponent(); SeriesCollection = new SeriesCollection { new RowSeries { Title = "2015", Values = new ChartValues<double> { 10, 50, 39, 50 } } }; //adding series will update and animate the chart automatically SeriesCollection.Add(new RowSeries { Title = "2016", Values = new ChartValues<double> { 11, 56, 42 } }); //also adding values updates and animates the chart automatically SeriesCollection[1].Values.Add(48d); Labels = new[] { "Maria", "Susan", "Charles", "Frida" }; Formatter = value => value.ToString("N"); }
public BasicLineExample() { InitializeComponent(); SeriesCollection = new SeriesCollection { new LineSeries { Title = "Series 1", Values = new ChartValues<double> { 4, 6, 5, 2 ,7 } }, new LineSeries { Title = "Series 2", Values = new ChartValues<double> { 6, 7, 3, 4 ,6 } } }; Labels = new[] {"Jan", "Feb", "Mar", "Apr", "May"}; YFormatter = value => value.ToString("C"); //modifying the series collection will animate and update the chart SeriesCollection.Add(new LineSeries { Values = new ChartValues<double> {5, 3, 2, 4}, LineSmoothness = 0 //straight lines, 1 really smooth lines }); //modifying any series values will also animate and update the chart SeriesCollection[2].Values.Add(5d); DataContext = this; }
public SalesViewModel() { var config = new SeriesConfiguration<SalesData>().Y(data => data.ItemsSold); Salesmen = new SeriesCollection(config) { new PieSeries { Title = "Charles", Values = new ChartValues<SalesData> { new SalesData {ItemsSold = 15, Rentability = .15, ItemsAverageSellPrice = 5000} } }, new PieSeries { Title = "Frida", Values = new ChartValues<SalesData> { new SalesData {ItemsSold = 16, Rentability = .12, ItemsAverageSellPrice = 5200} } }, new PieSeries { Title = "George", Values = new ChartValues<SalesData> { new SalesData {ItemsSold = 22, Rentability = .11, ItemsAverageSellPrice = 5100} } } }; }
public FilterChart() { InitializeComponent(); //create a configuration for City class var config = new SeriesConfiguration<City>() .Y(city => city.Population); // use Population an Y // X will use default config, a zero based index //create a series collection with this config Series = new SeriesCollection(config); //lets pull some initials results var results = DataBase.Cities.OrderByDescending(city => city.Population).Take(15).ToArray(); PopulationSeries = new BarSeries { Title = "Population by city 2015", Values = results.AsChartValues(), DataLabels = true }; //there are 2 types of labels, when we use a formatter, and a strong array mapping //in this case instead of a label formatter we use a strong array labels //since X is a zero based index LiveCharts automatically maps this array with X //so when X = 0 label will be labels[0], when X = 1 labels[1], X = 2 labels[2], X = n labels[n] Labels = results.Select(city => city.Name).ToArray(); Series.Add(PopulationSeries); DataContext = this; }
public MissingPointsExample() { InitializeComponent(); Series = new SeriesCollection { new LineSeries { Values = new ChartValues<double> { 4, 5, 7, 8, double.NaN, 5, 2, 8, double.NaN, 6, 2 } } }; DataContext = this; }
public FullyResponsiveExample() { InitializeComponent(); MyValues = new ChartValues<ObservableValue> { new ObservableValue(5), new ObservableValue(7), new ObservableValue(8), new ObservableValue(3) }; var lineSeries = new LineSeries { Values = MyValues, StrokeThickness = 4, Fill = new SolidColorBrush(Windows.UI.Colors.Transparent), PointGeometrySize = 0, DataLabels = true }; SeriesCollection = new SeriesCollection { lineSeries }; DataContext = this; }
public RotatedStackedBar() { InitializeComponent(); var config = new SeriesConfiguration<double>().X(val => val); SeriesCollection = new SeriesCollection(config) { new StackedBarSeries { Title = "Stacked Serie 1", Values = new double[] {3,6,2,7}.AsChartValues(), DataLabels = true }, new StackedBarSeries { Title = "Stacked Serie 1", Values = new double[] {6,3,5,2}.AsChartValues(), DataLabels = true }, new LineSeries { Title = "Line Series", Values = new double[] {10, 11, 8, 9}.AsChartValues(), Fill = Brushes.Transparent } }; DataContext = this; }
private static Chart InitializeBarGraph(SeriesCollection seriesCollection, string yAxisTitle) { var chart = new Chart(); //chart.Title = "Burndown"; chart.Type = ChartType.Combo; chart.TempDirectory = VirtualPathUtility.ToAbsolute("~/file/chart"); chart.SeriesCollection.Add(seriesCollection); chart.YAxis.Label.Text = yAxisTitle; chart.YAxis.Label.Color = System.Drawing.ColorTranslator.FromHtml("#CCCCCC"); chart.YAxis.DefaultTick.Label.Color = System.Drawing.ColorTranslator.FromHtml("#CCCCCC"); chart.XAxis.DefaultTick.Label.Color = System.Drawing.ColorTranslator.FromHtml("#CCCCCC"); chart.LegendBox.Visible = false; chart.BorderStyle = System.Web.UI.WebControls.BorderStyle.None; chart.TitleBox.Visible = false; chart.Background.Color = System.Drawing.ColorTranslator.FromHtml("#333333"); chart.DefaultSeries.Element.Color = System.Drawing.ColorTranslator.FromHtml("#1B12A6"); chart.DefaultElement.Color = System.Drawing.ColorTranslator.FromHtml("#1B12A6"); chart.Width = new System.Web.UI.WebControls.Unit(600, System.Web.UI.WebControls.UnitType.Pixel); chart.Height = new System.Web.UI.WebControls.Unit(400, System.Web.UI.WebControls.UnitType.Pixel); chart.Font.Name = "Helvetica"; chart.Font.Size = new System.Web.UI.WebControls.FontUnit(24, System.Web.UI.WebControls.UnitType.Pixel); chart.YAxis.Label.Font = new System.Drawing.Font("Helvetica", 8); chart.YAxis.DefaultTick.Label.Font = new System.Drawing.Font("Helvetica", 8); chart.XAxis.DefaultTick.Label.Font = new System.Drawing.Font("Helvetica", 8); //NOTE: needed to do this for the old version of .net charting (3.4). chart.FileManager.TempDirectory = VirtualPathUtility.ToAbsolute("~/file/chart"); chart.FileManager.SaveImage(chart.GetChartBitmap()); //chart.FileManager.FileName = chart.FileManager.TempDirectory + "/" + chart.FileManager.FileName + ".png"; return chart; }
public EnergyPredictionExample() { InitializeComponent(); Series = new SeriesCollection { new StackedAreaSeries { Values = new ChartValues<double> {20, 30, 35, 45, 65, 85}, Title = "Electricity" }, new StackedAreaSeries { Values = new ChartValues<double> {10, 12, 18, 20, 38, 40}, Title = "Water" }, new StackedAreaSeries { Values = new ChartValues<double> {5, 8, 12, 15, 22, 25}, Title = "Solar" }, new StackedAreaSeries { Values = new ChartValues<double> {10, 12, 18, 20, 38, 40}, Title = "Gas" } }; DataContext = this; }
public SeriesCollection FetchAll() { var coll = new SeriesCollection(); var qry = new Query(Series.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }
public Statistic(int episodeCount, double meanScore, SeriesCollection scoreDistribution, string[] scoreRatings, int serieCount) { EpisodeCount = episodeCount; MeanScore = meanScore; ScoreDistribution = scoreDistribution; SerieCount = serieCount; ScoreRatings = scoreRatings; }
public DateTime() { InitializeComponent(); var dayConfig = Mappers.Xy<DateModel>() .X(dayModel => (double) dayModel.DateTime.Ticks/TimeSpan.FromHours(1).Ticks) .Y(dayModel => dayModel.Value); //Notice you can also configure this type globally, so you don't need to configure every //SeriesCollection instance using the type. //more info at http://lvcharts.net/App/Index#/examples/v1/wpf/Types%20and%20Configuration Series = new SeriesCollection(dayConfig) { new LineSeries { Values = new ChartValues<DateModel> { new DateModel { DateTime = System.DateTime.Now, Value = 5 }, new DateModel { DateTime = System.DateTime.Now.AddHours(2), Value = 9 } }, Fill = Brushes.Transparent }, new ColumnSeries { Values = new ChartValues<DateModel> { new DateModel { DateTime = System.DateTime.Now, Value = 4 }, new DateModel { DateTime = System.DateTime.Now.AddHours(1), Value = 6 }, new DateModel { DateTime = System.DateTime.Now.AddHours(2), Value = 8 } } } }; Formatter = value => new System.DateTime((long) (value*TimeSpan.FromHours(1).Ticks)).ToString("t"); DataContext = this; }
public Chart(List<DateTime> dateList,List<int> dataList,string xTitle,string yTitle) { InitializeComponent(); YTitle = yTitle; XTitle = xTitle; date = dateList; data = dataList; if (date.Count == 0) return; if(date.Count==1) { date.Add(date[0]); DateTime prev = date[0].AddDays(-1); date[0]=prev; data.Add(data[0]); } if(date.Count>0 && date.Count<step) { From = date[0].Date.AddYears(1899).AddDays(-1).ToOADate(); To = date[date.Count-1].Date.AddYears(1899).AddDays(-1).ToOADate(); } if (date.Count >= step) { To = date[date.Count - 1].Date.AddYears(1899).AddDays(-1).ToOADate(); //установка границ отрисовки графика From = (To-step); } left= date[0].Date.AddYears(1899).AddDays(-1).ToOADate(); right= date[date.Count - 1].Date.AddYears(1899).AddDays(-1).ToOADate(); SetYScale(); var dayConfig = Mappers.Xy<DateModel>() .X(dateModel => dateModel.DateTime.Ticks / TimeSpan.FromDays(1).Ticks) .Y(dateModel => dateModel.Value); //распределение данных по осям Series = new SeriesCollection(dayConfig) { new LineSeries //создание линии { Title=yTitle, Values = GetData(date,data), StrokeThickness = 1, DataLabels=true, } }; res = To - From; curStep = step; Formatter = value => new DateTime((long)(value * TimeSpan.FromDays(1).Ticks)).ToString("dd MMM yyyy"); //форматирование оси x DataContext = this; }
public DarkPanelControlVm() { _timer.Interval = TimeSpan.FromMilliseconds(1000); _timer.Tick += TimerOnTick; _timer.Start(); AngularGaugeValue = 50; Yes = new ObservableValue(10); No = new ObservableValue(6); Maybe = new ObservableValue(4); Line1 = new ChartValues<ObservableValue> { new ObservableValue(3), new ObservableValue(5), new ObservableValue(1), new ObservableValue(6), new ObservableValue(8), new ObservableValue(3), new ObservableValue(6), new ObservableValue(3) }; PieSeries = new SeriesCollection { new PieSeries {Title = "Yes",Values = new ChartValues<ObservableValue> {Yes}}, new PieSeries {Title = "No", Values = new ChartValues<ObservableValue> {Maybe}}, new PieSeries {Title = "Maybe", Values = new ChartValues<ObservableValue> {Maybe}} }; GeoValues = new Dictionary<string, double>(); var r = new Random(); GeoValues["MX"] = r.Next(0, 100); GeoValues["RU"] = r.Next(0, 100); GeoValues["CA"] = r.Next(0, 100); GeoValues["US"] = r.Next(0, 100); GeoValues["IN"] = r.Next(0, 100); GeoValues["CN"] = r.Next(0, 100); GeoValues["JP"] = r.Next(0, 100); GeoValues["BR"] = r.Next(0, 100); GeoValues["DE"] = r.Next(0, 100); GeoValues["FR"] = r.Next(0, 100); GeoValues["GB"] = r.Next(0, 100); DynamicValues = new ChartValues<ObservableValue> { new ObservableValue(1), new ObservableValue(5), new ObservableValue(4), new ObservableValue(7), new ObservableValue(4), new ObservableValue(8) }; Formatter = x => x.ToString("P"); }
SeriesCollection GetDonationData (OrganizationMetadata metadata, out decimal donationsTotal, out int donationCount) { SeriesCollection collection = new SeriesCollection(); DateTime dateIterator = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); Organization org = Organization.FromIdentity(metadata.OrganizationId); if (DateTime.Now.Day > 4) { dateIterator = dateIterator.AddMonths(-1); } else { dateIterator = dateIterator.AddMonths(-1); // -2 } DateTime dateStop = dateIterator.AddMonths(1); FinancialAccountRows rows = org.FinancialAccounts.IncomeDonations.GetRows(dateIterator, dateIterator.AddMonths(1)); Series series = new Series(); series.Name = ""; DateTime today = DateTime.Now.Date; int rowIndex = 0; donationsTotal = 0.0m; donationCount = rows.Count; Dictionary<int, int> personMembershipCountLookup = new Dictionary<int, int>(); while (dateIterator < dateStop) { decimal donationsToday = 0.0m; DateTime nextDate = dateIterator.AddDays (1); while (rowIndex < rows.Count && rows[rowIndex].TransactionDateTime < nextDate) { donationsToday -= rows[rowIndex].Amount; donationsTotal -= rows[rowIndex].Amount; rowIndex++; } Element newElement = new Element(); newElement.XDateTime = dateIterator; newElement.YValue = (double) donationsToday; series.Elements.Add(newElement); dateIterator = nextDate; } collection.Add(series); collection[0].DefaultElement.Color = metadata.Color; return collection; }
public HighPerformanceLine() { InitializeComponent(); //First you need to install LiveCharts.Optimizations //from Nuget: //Install-Package LiveCharts.Optimizations //LiveCharts.Optimization contains a class called ChartOptimizations where you can find //algorithms according to your chart type, they also have a good description, indicating //which is the best according to your case, using a wrong algorithm could not display data //to an optimized quality. //var algorithm = ChartOptimizations.Lines.RegularX<double>() // // low quality is the default, but it is really accurate, it could fail only for +-3 pixels // .WithQuality(DataQuality.Low); //create a configuration in this case we will use X as a zero based index, //and Y as the stored value in Series.Values //we will also attach the algorithm we just selected. var config = new SeriesConfiguration<double>() .X((val, index) => index) .Y(val => val); //.HasHighPerformanceMethod(algorithm); //create a SeriesCollection with this configuration Series = new SeriesCollection(config); //create a new line series var line = new LineSeries {Values = new ChartValues<double>()}; //add some random values to test var r = new Random(); var trend = 0d; for (var i = 0; i < 1000000; i++) { if (i%1000 == 0) trend += r.Next(-500, 500); line.Values.Add(trend + r.Next(-10, 10)); } Series.Add(line); //some format var now = DateTime.Now.ToOADate(); XFormat = val => DateTime.FromOADate(now + val/100).ToShortDateString(); YFormat = val => Math.Round(val) + " ms"; //set zooming if needed. ZoomingMode = ZoomingOptions.XY; DataContext = this; }
public MathViewModel() { Functions = new SeriesCollection(new SeriesConfiguration<Point>().X(pt => pt.X).Y(pt => pt.Y)) { new ScatterSeries { Values = _evaluateAt.Select(x => new Point(x, _baseFunc(x,0))).AsChartValues(), PointRadius = 0, StrokeThickness = 4 } }; }
/// <summary>метод который формирует данные для chart-а на основе колекции серий, /// поинтов и их пересечений </summary> private SeriesCollection FillData( Dictionary<string, float> seriesDef, Dictionary<string, float> pointDef, Dictionary<Intersection, float> intersections) { SeriesCollection result = new SeriesCollection(); if (!subDiagramMode) { switch (this.DiagramType) { case DiagramTypeEnum.Graph: result.Add(CreateDataForFullDiagram(seriesDef, pointDef, intersections, true)); break; case DiagramTypeEnum.ColumnDetail: result.Add(CreateDataForFullDiagram(seriesDef, pointDef, intersections, false)); break; case DiagramTypeEnum.ColumnGeneral: result.Add(CreateDataForColumnGeneral(seriesDef)); break; case DiagramTypeEnum.PieGeneral: result.Add(CreateDataForPieGeneral(seriesDef)); break; case DiagramTypeEnum.Speedometer: case DiagramTypeEnum.TrafficLight: if (seriesDef.Any( s => s.Key.Equals(defaultSeries))) result.Add(FillSeriesData(seriesDef.First(s => s.Key.Equals(defaultSeries)))); break; case DiagramTypeEnum.PieDetail: if (seriesDef.Any(s => s.Key.Equals(defaultSeries))) result.Add(FillPointsData(seriesDef.First(s => s.Key.Equals(defaultSeries)), pointDef, intersections, false)); break; } } else { if (string.IsNullOrEmpty(detalizedSeriesName)) detalizedSeriesName = this.defaultSeries; if (seriesDef.Any(s => s.Key.Equals(detalizedSeriesName))) { switch (this.SubDiagramType) { case SubDiagramTypeEnum.Graph: case SubDiagramTypeEnum.ColumnDetail: case SubDiagramTypeEnum.PieDetail: result.Add(FillPointsData(seriesDef.First(s => s.Key.Equals(detalizedSeriesName)), pointDef, intersections, false)); break; } } } FillEmptyVisibleSeries(seriesDef.Keys.ToList()); return result; }
SeriesCollection GetGrowthData() { string cacheDataKey = "ChartData-AllMembershipEvents"; MembershipEvents events = (MembershipEvents)Cache.Get(cacheDataKey); if (events == null) { events = MembershipEvents.LoadAll(); Cache.Insert(cacheDataKey, events, null, DateTime.Today.AddDays(1).ToUniversalTime(), System.Web.Caching.Cache.NoSlidingExpiration); } /* * using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/Data/MembershipEvents.xml"))) * { * string xml = reader.ReadToEnd(); * * events = MembershipEvents.FromXml(xml); * }*/ SeriesCollection collection = new SeriesCollection(); DateTime dateIterator = new DateTime(2006, 1, 1); string timeFocus = Request.QueryString["DaysHistory"]; if (timeFocus != null) { dateIterator = DateTime.Now.Date.AddDays(-Int32.Parse(timeFocus)); } Series series = new Series(); series.Name = ""; DateTime today = DateTime.Now.Date; int eventIndex = 0; int currentCount = 0; while (dateIterator < today) { DateTime nextDate = dateIterator.AddDays(1); while (eventIndex < events.Count && events[eventIndex].DateTime < nextDate) { if (events[eventIndex].OrganizationId == Organization.PPSEid) { currentCount += events[eventIndex].DeltaCount; } eventIndex++; } Element newElement = new Element(); newElement.XDateTime = dateIterator; newElement.YValue = currentCount; series.Elements.Add(newElement); dateIterator = nextDate; } collection.Add(series); collection[0].DefaultElement.Color = Color.FromArgb(49, 255, 49); return(collection); }
//----- #endregion /YearForDailyChartTextBox #region CheckYearlyFinancialButton_Click private void CheckYearlyFinancialButton_Click(object sender, EventArgs e) { string errorMessage; if (Year_Int == 0) { errorMessage = "لطفا سال مورد نظر را وارد نمایید!"; Mbb.Windows.Forms.MessageBox.Show(text: errorMessage, caption: "خطای ورودی", icon: Mbb.Windows.Forms.MessageBoxIcon.Error, button: Mbb.Windows.Forms.MessageBoxButtons.Ok); yearForDailyChartTextBox.Focus(); return; } else { errorMessage = null; string checkDate = $"{Year_Int}"; DataBaseContext dataBaseContext = null; try { dataBaseContext = new DataBaseContext(); List <MonthlyFinancial> monthlyFinancials = null; monthlyFinancials = dataBaseContext.MonthlyFinancials .Where(current => current.Register_Date.Contains(checkDate)) .OrderBy(current => current.Month) .ToList(); if (monthlyFinancials.Count == 0) { Mbb.Windows.Forms.MessageBox.Show( text: "اطلاعاتی برای تاریخ مورد نظر یافت نگردید!", caption: "جستجوی ناموفق", icon: Mbb.Windows.Forms.MessageBoxIcon.Error, button: Mbb.Windows.Forms.MessageBoxButtons.Ok); checkYearlyFinancialButton.Enabled = true; return; } else { monthlyFinancialDataGridView.DataSource = monthlyFinancials; checkYearlyFinancialButton.Enabled = true; } } catch (Exception ex) { Infrastructure.Utility.ExceptionShow(ex); } finally { if (dataBaseContext != null) { dataBaseContext.Dispose(); dataBaseContext = null; } } } viewMonthlyFinancialCartesianChart.Series.Clear(); SeriesCollection series = new SeriesCollection(); var years = (from o in monthlyFinancialDataGridView.DataSource as List <MonthlyFinancial> select new { Year = o.Year, }).Distinct(); #region Sum Total Price Of Month foreach (var year in years) { List <int> values = new List <int>(); for (int month = 1; month <= 12; month++) { int totalPrice = 0; var data = from o in monthlyFinancialDataGridView.DataSource as List <MonthlyFinancial> where o.Year.Equals(year.Year) && o.Month.Equals(month) orderby o.Month ascending select new { o.Sum_Total_Price_Of_Month, o.Month }; if (data.SingleOrDefault() != null) { totalPrice = int.Parse(data.FirstOrDefault().Sum_Total_Price_Of_Month); } values.Add(totalPrice); } series.Add(new LineSeries() { Title = $"جمع کل حساب ماه", Values = new ChartValues <int>(values) }); viewYearlyFinancialCartesianChart.Series = series; } #endregion /Sum Total Price Of Day #region Sum Payment Amount Of Month foreach (var year in years) { List <int> values = new List <int>(); for (int month = 1; month <= 12; month++) { int paymentAmount = 0; var data = from o in monthlyFinancialDataGridView.DataSource as List <MonthlyFinancial> where o.Year.Equals(year.Year) && o.Month.Equals(month) orderby o.Month ascending select new { o.Sum_Payment_Amount_Of_Month, o.Month }; if (data.SingleOrDefault() != null) { paymentAmount = int.Parse(data.FirstOrDefault().Sum_Payment_Amount_Of_Month); } values.Add(paymentAmount); } series.Add(new LineSeries() { Title = "جمع کل پرداختی ماه", Values = new ChartValues <int>(values) }); viewYearlyFinancialCartesianChart.Series = series; } #endregion /Sum Payment Amount Of Month #region Sum Remaining Amount Of Month foreach (var year in years) { List <int> values = new List <int>(); for (int month = 1; month <= 12; month++) { int remainingAmount = 0; var data = from o in monthlyFinancialDataGridView.DataSource as List <MonthlyFinancial> where o.Year.Equals(year.Year) && o.Month.Equals(month) orderby o.Month ascending select new { o.Sum_Remaining_Amount_Of_Month, o.Month }; if (data.SingleOrDefault() != null) { remainingAmount = int.Parse(data.FirstOrDefault().Sum_Remaining_Amount_Of_Month); } values.Add(remainingAmount); } series.Add(new LineSeries() { Title = "جمع کل بدهی ماه", Values = new ChartValues <int>(values) }); viewYearlyFinancialCartesianChart.Series = series; } #endregion /Sum Remaining Amount Of Month }
public CategoryChartViewModel() { PieSeries = new SeriesCollection(); Series = new List <Series>(); }
public void ChangeCustomLine(string title, ChartValues <ObservableValue> points) { var rand = new Random(); SeriesCollection seriesCollection = Graphics; LineSeries Line = (LineSeries)seriesCollection.Where(x => x.Title == title).FirstOrDefault(); ChartValues <ObservableValue> line = (ChartValues <ObservableValue>)Line.Values; try { //удаленные точки if (line.Count > points.Count) { if (points.Count == 0) { if (App.Language == CultureInfo.GetCultureInfoByIetfLanguageTag("ru-RU")) { MessageBox.Show("Нельзя создать график без точек", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning); return; } else { MessageBox.Show("You cannot create a graph without points", "Error", MessageBoxButton.OK, MessageBoxImage.Warning); return; } } if (points.Count == 1) { if (App.Language == CultureInfo.GetCultureInfoByIetfLanguageTag("ru-RU")) { MessageBox.Show("График должен состоять хотя бы из 2 точек", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning); return; } else { MessageBox.Show("The graph must contain at least 2 points", "Error", MessageBoxButton.OK, MessageBoxImage.Warning); return; } } for (int i = line.Count; i > 0; i--) { if (points.Count <= i - 1) { line.Remove(line[i - 1]); } else { line[i - 1] = points[i - 1]; } } } //перенос точек for (int i = line.Count; i > 0; i--) { line[i - 1] = points[i - 1]; } //добавление новых точек if (line.Count < points.Count) { for (int i = line.Count; i < points.Count; i++) { line.Add(points[i]); } } } //ошибка может возникнуть при закрытии окна catch (Exception ex) { } }
private void UpdateLineGraph() { DateTime now = DateTime.Now; cartesianChart1.AxisX[0].Labels.Add(now.ToShortTimeString()); SeriesCollection lineseries2 = new SeriesCollection(); using (WorkshopEntities7 db = new WorkshopEntities7()) { if (selectedgroup == "Adults") { var data = db.Adults; var users = (from o in data orderby o.username select o.username).Distinct(); //fuking retard code int lineCounter = 0; if (users.Count() != cartesianChart1.Series.Count()) //in case new one's data added after running ShowLingraph { //conflict between number of users and number of Series occur lineseries2.Clear(); GetTableData(); ShowLineGraph(); return; } foreach (var user in users) { var iValues = cartesianChart1.Series[lineCounter].Values; double latestvalue = 0; var userdatas = from oo in data where oo.username.Equals(user) && (60 * SqlFunctions.DatePart("hour", oo.Date)) + (SqlFunctions.DatePart("minute", oo.Date)) == (60 * SqlFunctions.DatePart("hour", now)) + (SqlFunctions.DatePart("minute", now)) && oo.time < 60 select new { oo.time, oo.Date }; if (userdatas.FirstOrDefault() != null) { latestvalue = (double)userdatas.FirstOrDefault().time; } iValues.Add(latestvalue); //cartesianChart1.Series[lineCounter].Values.Add(latestvalue); lineCounter++; LineSeries line = new LineSeries() { Title = user.ToString(), DataLabels = false, Values = iValues, }; lineseries2.Add(line); } } else if (selectedgroup == "Students") { var data = db.Students; var users = (from o in data orderby o.username select o.username).Distinct(); //fuking retard code int lineCounter = 0; if (users.Count() != cartesianChart1.Series.Count()) //in case new one's data added after running ShowLingraph { //conflict between number of users and number of Series occur lineseries2.Clear(); GetTableData(); ShowLineGraph(); return; } foreach (var user in users) { var iValues = cartesianChart1.Series[lineCounter].Values; double latestvalue = 0; var userdatas = from oo in data where oo.username.Equals(user) && (60 * SqlFunctions.DatePart("hour", oo.Date)) + (SqlFunctions.DatePart("minute", oo.Date)) == (60 * SqlFunctions.DatePart("hour", now)) + (SqlFunctions.DatePart("minute", now)) && oo.time < 60 select new { oo.time, oo.Date }; if (userdatas.FirstOrDefault() != null) { latestvalue = (double)userdatas.FirstOrDefault().time; } iValues.Add(latestvalue); //cartesianChart1.Series[lineCounter].Values.Add(latestvalue); lineCounter++; LineSeries line = new LineSeries() { Title = user.ToString(), DataLabels = false, Values = iValues, }; lineseries2.Add(line); } } else { var data = db.voicerecords; var users = (from o in data orderby o.username select o.username).Distinct(); //fuking retard code int lineCounter = 0; if (users.Count() != cartesianChart1.Series.Count()) //in case new one's data added after running ShowLingraph { //conflict between number of users and number of Series occur lineseries2.Clear(); GetTableData(); ShowLineGraph(); return; } foreach (var user in users) { var iValues = cartesianChart1.Series[lineCounter].Values; double latestvalue = 0; var userdatas = from oo in data where oo.username.Equals(user) && (60 * SqlFunctions.DatePart("hour", oo.Date)) + (SqlFunctions.DatePart("minute", oo.Date)) == (60 * SqlFunctions.DatePart("hour", now)) + (SqlFunctions.DatePart("minute", now)) && oo.time < 60 select new { oo.time, oo.Date }; if (userdatas.FirstOrDefault() != null) { latestvalue = (double)userdatas.FirstOrDefault().time; } iValues.Add(latestvalue); //cartesianChart1.Series[lineCounter].Values.Add(latestvalue); lineCounter++; LineSeries line = new LineSeries() { Title = user.ToString(), DataLabels = false, Values = iValues, }; lineseries2.Add(line); } } cartesianChart1.Series = lineseries2; } cartesianChart1.AxisX[0].MaxValue = double.NaN; }
private SeriesCollection GetTableData() { SeriesCollection columnseries = new SeriesCollection(); DateTime now = DateTime.Now; ColumnSeries column = new ColumnSeries() { Title = now.AddMinutes(-chartRangeMinute).ToShortTimeString() + "~" + now.AddMinutes(-chartRangeMinute / 2).ToShortTimeString(), DataLabels = false, Values = new ChartValues <double>(), //LabelPoint = point => point.Y.ToString() }; ColumnSeries column2 = new ColumnSeries() { Title = now.AddMinutes(-chartRangeMinute / 2).ToShortTimeString() + "~" + now.ToShortTimeString(), DataLabels = false, Values = new ChartValues <double>(), //LabelPoint = point => point.Y.ToString() }; using (WorkshopEntities7 db = new WorkshopEntities7()) { if (selectedgroup == "Adults") { var data = db.Adults; var users = (from o in data orderby o.username select o.username).Distinct(); //SeriesCollection lineseries = new SeriesCollection(); foreach (var user in users) { LineSeries line = new LineSeries() { Title = user.ToString(), DataLabels = false, Values = new ChartValues <double>(), //Values=userdatas.AsChartValues() }; //double totalseconds1 = 5; //double totalseconds2 = 5; var timesForCulumn1 = new List <double>(); var timesForCulumn2 = new List <double>(); for (DateTime itime = now.AddMinutes(-chartRangeMinute); itime < now; itime = itime.AddMinutes(1)) { double vv = 0; //var ruleDate = Convert.ToDateTime(itime).TimeOfDay; var userdatas = from oo in data where SqlFunctions.DatePart("minute", oo.Date) == SqlFunctions.DatePart("minute", itime) && oo.username.Equals(user) && SqlFunctions.DatePart("hour", oo.Date) == SqlFunctions.DatePart("hour", itime) && oo.time < 60 select oo.time; Console.WriteLine(itime.ToShortTimeString()); if (userdatas.FirstOrDefault() != null) { vv = (double)userdatas.FirstOrDefault(); } line.Values.Add(vv); if (itime.TimeOfDay < now.AddMinutes(-chartRangeMinute / 2).TimeOfDay) { //totalseconds1 = totalseconds1 + vv; timesForCulumn1.Add(vv); } else { //totalseconds2 = totalseconds2 + vv; timesForCulumn2.Add(vv); } } if (firstflag) { lineseries.Add(line); } //column.Values.Add(totalseconds1); //column2.Values.Add(totalseconds2); column.Values.Add(timesForCulumn1.Sum() + 5); column2.Values.Add(timesForCulumn2.Sum() + 5); } firstflag = false; //cartesianChart1.Series = series; columnseries.Add(column); columnseries.Add(column2); } else { var data = db.Students; var users = (from o in data orderby o.username select o.username).Distinct(); //SeriesCollection lineseries = new SeriesCollection(); foreach (var user in users) { LineSeries line = new LineSeries() { Title = user.ToString(), DataLabels = false, Values = new ChartValues <double>(), //Values=userdatas.AsChartValues() }; //double totalseconds1 = 5; //double totalseconds2 = 5; var timesForCulumn1 = new List <double>(); var timesForCulumn2 = new List <double>(); for (DateTime itime = now.AddMinutes(-chartRangeMinute); itime < now; itime = itime.AddMinutes(1)) { double vv = 0; //var ruleDate = Convert.ToDateTime(itime).TimeOfDay; var userdatas = from oo in data where SqlFunctions.DatePart("minute", oo.Date) == SqlFunctions.DatePart("minute", itime) && oo.username.Equals(user) && SqlFunctions.DatePart("hour", oo.Date) == SqlFunctions.DatePart("hour", itime) && oo.time < 60 select oo.time; Console.WriteLine(itime.ToShortTimeString()); if (userdatas.FirstOrDefault() != null) { vv = (double)userdatas.FirstOrDefault(); } line.Values.Add(vv); if (itime.TimeOfDay < now.AddMinutes(-chartRangeMinute / 2).TimeOfDay) { //totalseconds1 = totalseconds1 + vv; timesForCulumn1.Add(vv); } else { //totalseconds2 = totalseconds2 + vv; timesForCulumn2.Add(vv); } } if (firstflag) { lineseries.Add(line); } //column.Values.Add(totalseconds1); //column2.Values.Add(totalseconds2); column.Values.Add(timesForCulumn1.Sum() + 5); column2.Values.Add(timesForCulumn2.Sum() + 5); } firstflag = false; //cartesianChart1.Series = series; columnseries.Add(column); columnseries.Add(column2); } } return(columnseries); }
protected void dgInfoView_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { if (String.Compare(((DataRowView)e.Item.DataItem).Row[0].ToString(), "Display Status:", true) == 0) { DataSet iSet = PE_DAL.GetROODisplayStatusView(this.PubID); if (iSet.Tables[0].Rows.Count > 0) { Label l_displayStatus = new Label(); foreach (DataRow s in iSet.Tables[0].Rows) { if (l_displayStatus.Text.Length > 0) { l_displayStatus.Text += ", "; } l_displayStatus.Text += s.ItemArray[1].ToString(); } l_displayStatus.Text.Trim(); ((DataRowView)e.Item.DataItem).Row[0] = ""; e.Item.Cells[1].Controls.Clear(); e.Item.Cells[1].Controls.Add(l_displayStatus); } else { Label errLbl = new Label(); errLbl.Text = " - "; e.Item.Cells[1].Controls.Clear(); e.Item.Cells[1].Controls.Add(errLbl); } } else if (String.Compare(((DataRowView)e.Item.DataItem).Row[0].ToString(), "Subject:", true) == 0) { DataGrid dgRegReimb = new DataGrid(); dgRegReimb.ID = "innerDgRegReimb"; //Format the DataGrid to look cool. dgRegReimb.BorderWidth = (Unit)0; dgRegReimb.CellPadding = 4; dgRegReimb.CellSpacing = 0; dgRegReimb.GridLines = GridLines.None; dgRegReimb.BorderColor = Color.FromName("#E0E0E0"); dgRegReimb.ItemStyle.BackColor = Color.White; dgRegReimb.AlternatingItemStyle.BackColor = Color.FromName("LightGray"); dgRegReimb.ShowHeader = false; dgRegReimb.HeaderStyle.CssClass = "fieldLabel"; dgRegReimb.HeaderStyle.BackColor = Color.FromName("#ffff00"); dgRegReimb.AutoGenerateColumns = false; //****Add a series of BoundColumns****// //***Region Name***// BoundColumn bc = new BoundColumn(); //Set the BoundColumn Values bc.DataField = "Description"; //bc.HeaderText = "Region(s)"; bc.ItemStyle.Wrap = false; bc.ItemStyle.CssClass = "fieldLabel"; dgRegReimb.Columns.Add(bc); //****End BoundColumns****// DataSet iSet = PE_DAL.GetROOSubjectView(this.PubID); if (iSet != null) { dgRegReimb.DataSource = iSet; dgRegReimb.DataBind(); ((DataRowView)e.Item.DataItem).Row[0] = ""; e.Item.Cells[1].Controls.Clear(); e.Item.Cells[1].Controls.Add(dgRegReimb); } else { Label errLbl = new Label(); errLbl.Text = " - "; e.Item.Cells[1].Controls.Clear(); e.Item.Cells[1].Controls.Add(errLbl); } } //NCIPL_CC - Part of changes to have collections on NCIPL tab and ROO tab else if (String.Compare(((DataRowView)e.Item.DataItem).Row[0].ToString(), "Collections:", true) == 0) { //For Displaying Collections DataGrid dgCollectionsView = new DataGrid(); dgCollectionsView.ID = "innerdgCollectionsView"; //Format the DataGrid to look cool. dgCollectionsView.BorderWidth = (Unit)0; dgCollectionsView.CellPadding = 4; dgCollectionsView.CellSpacing = 0; dgCollectionsView.GridLines = GridLines.None; dgCollectionsView.BorderColor = Color.FromName("#E0E0E0"); dgCollectionsView.ItemStyle.BackColor = Color.White; dgCollectionsView.AlternatingItemStyle.BackColor = Color.FromName("LightGray"); dgCollectionsView.ShowHeader = false; dgCollectionsView.HeaderStyle.CssClass = "fieldLabel"; dgCollectionsView.HeaderStyle.BackColor = Color.FromName("#ffff00"); dgCollectionsView.AutoGenerateColumns = false; //****Add a series of BoundColumns****// //***Region Name***// BoundColumn bc = new BoundColumn(); //Set the BoundColumn Values //bc.DataField = "Description"; bc.DataField = "SeriesName"; //bc.HeaderText = "Region(s)"; bc.ItemStyle.Wrap = false; bc.ItemStyle.CssClass = "fieldLabel"; dgCollectionsView.Columns.Add(bc); //****End BoundColumns****// //DataSet iSet = PE_DAL.GetNCIPLStacksView(this.PubID); SeriesCollection iSet = PE_DAL.GetCollectionsByInterfaceByPubId("NCIPL_CC", this.PubID); //if (iSet != null) if (iSet.Count > 0) { dgCollectionsView.DataSource = iSet; dgCollectionsView.DataBind(); ((DataRowView)e.Item.DataItem).Row[0] = ""; e.Item.Cells[1].Controls.Clear(); e.Item.Cells[1].Controls.Add(dgCollectionsView); } else { Label errLbl = new Label(); errLbl.Text = " - "; e.Item.Cells[1].Controls.Clear(); e.Item.Cells[1].Controls.Add(errLbl); } } } }
public void RefreshCostChart() { if (selectedMonth == -1) { // per month aggregateCostMonth(); Labels = AggregationMonth; } else if (selectedWeek == -1) { // per week aggregateCostWeek(); Labels = AggregationWeek; } else { // per day aggregateCostDay(); Labels = AggregationDay; } SeriesLineCollection = new SeriesCollection(); SeriesBarCollection = new SeriesCollection(); // Remake the Two Charts List <int> costsInt = new List <int>(); foreach (var cost in costs) { costsInt.Add((int)cost.Value); } SeriesLineCollection.Add(new LineSeries { Title = "Your Costs", Values = new ChartValues <int>(costsInt) }); SeriesBarCollection.Add(new ColumnSeries { Title = "Your Costs", Values = new ChartValues <int>(costsInt) }); AxisYTitle = "Cost"; YFormatter = value => value.ToString("C"); double maxValue = 0; for (int i = 0; i < costs.Count; ++i) { double num = costsInt[i]; if (maxValue < num) { maxValue = num; } } setStepSeperator((int)maxValue, costs.Count); // Notify The binded labels in the view if (null != PropertyChanged) { PropertyChanged(this, new PropertyChangedEventArgs("SeriesLineCollection")); PropertyChanged(this, new PropertyChangedEventArgs("SeriesBarCollection")); PropertyChanged(this, new PropertyChangedEventArgs("YFormatter")); PropertyChanged(this, new PropertyChangedEventArgs("Labels")); PropertyChanged(this, new PropertyChangedEventArgs("AxisYTitle")); } }
private void RefreshAction(object obj) { var dataKec = (from a in DataAccess.DataBasic.DataPendudukPerKecamatan() select a); var groupPengaduan = DataAccess.DataBasic.DataPengaduan.GroupBy(x => x.KodeDistrik); List <double> rasio = new List <double>(); List <double> jumlahKorbanAnak = new List <double>(); datgrafirk.Clear(); foreach (var kec in dataKec) { var model = new GrafikModel { Kategori = kec.Nama, Series = kec.Nama }; var kasus = groupPengaduan.Where(x => x.Key == kec.Id).FirstOrDefault(); if (kasus != null) { var listkasusAnak = (from p in kasus from korban in p.Korban where korban.TanggalLahir != null let age = p.TanggalLapor.Value.Year - korban.TanggalLahir.Year group p by age < 18 ? "Anak" :"Dewasa" into ages select new { Age = ages.Key, Persons = ages }); Double kasusAnak = listkasusAnak.Where(x => x.Age == "Anak").Count(); var total = kasusAnak + listkasusAnak.Where(x => x.Age == "Dewasa").Count(); double data = (Convert.ToDouble((kasusAnak / kec.Total) * 1000)); rasio.Add(Math.Round(data, 2)); jumlahKorbanAnak.Add(kasusAnak); model.Nilai = Math.Round(data, 2); model.Nilai2 = kasusAnak; } else { rasio.Add(0); jumlahKorbanAnak.Add(0); model.Nilai = 0; model.Nilai2 = 0; } datgrafirk.Add(model); } SeriesCollection = new SeriesCollection { new LineSeries { Title = "Rasio", Values = new ChartValues <double>(rasio), }, new ColumnSeries { Title = "Jumlah Korban Anak", Values = new ChartValues <double>(jumlahKorbanAnak) } }; Labels = (from a in DataAccess.DataBasic.GetKecamatan() select a.Nama).ToArray(); //new[] { "Jan", "Feb", "Mar", "Apr", "May" }; //YFormatter = value => value.ToString("C"); }
//{ // new CuadroInicio{ Titulo="Obras en proceso",Cantidad="10", Icono=MaterialDesignThemes.Wpf.PackIconKind.AccountBalance}, // new CuadroInicio{ Titulo="Dinero Caja",Cantidad="1000", Icono=MaterialDesignThemes.Wpf.PackIconKind.AccountBalance}, // new CuadroInicio{ Titulo="Obras en proceso",Cantidad="10", Icono=MaterialDesignThemes.Wpf.PackIconKind.AccountBalance} //};] public async Task Inicializar() { try { var totalIngreso = 0d; var totalEgreso = 0d; var cashflow = new ChartValues <DateModel>(); var egresos = new ChartValues <DateModel>(); CuentaCorrientes = new ObservableCollection <CuentaCorrienteDto>(await Servicios.ApiProcessor.GetApi <CuentaCorrienteDto[]>("CuentaCorriente/GetAll")); ComprobanteCompras = new ObservableCollection <ComprobanteCompraDto>(await ApiProcessor.GetApi <ComprobanteCompraDto[]>("ComprobanteCompra/GetAll")); var comprobanteSalida = await ApiProcessor.GetApi <decimal[]>("ComprobanteSalida/GetPorcentaje"); var comprobanteEntrada = await ApiProcessor.GetApi <decimal[]>("ComprobanteEntrada/GetPorcentaje"); DetalleCaja = new ObservableCollection <DetalleCajaDto>(await Servicios.ApiProcessor.GetApi <DetalleCajaDto[]>("DetalleCaja/GetAll")); Oficina = await ApiProcessor.GetApi <decimal>("ComprobanteCompra/GetOficina"); Jornales = new ObservableCollection <JornalDto>(await ApiProcessor.GetApi <JornalDto[]>("Jornal/GetAll")); Jornales.Sum(x => x.Repuestos); Jornales.Sum(x => x.Gasolina); Obras = await ApiProcessor.GetApi <int[]>("Obra/NumeroPendientes"); Presupuestos = new ObservableCollection <PresupuestoDto>(await ApiProcessor.GetApi <PresupuestoDto[]>("Presupuesto/GetAprobado")); if (CuentaCorrientes != null) { foreach (var i in CuentaCorrientes) { Operaciones = new List <OperacionDto>(await ApiProcessor.GetApi <OperacionDto[]>($"Operacion/GetByBanco/{i.BancoId}")); var values = new ChartValues <DateModel>(); var total = 0d; foreach (var item in Operaciones.Where(x => x.FechaEmision.Value.Year == DateTime.Now.Year).OrderBy(x => x.FechaEmision)) { if (item.Haber != 0) { total -= (double)item.Haber; totalEgreso += (double)item.Haber; Graficas.Add(new ClaseGrafico { Fecha = item.FechaEmision.Value, TipoMovimiento = TipoMovimiento.Egreso, Monto = (decimal)item.Haber }); } else { total += (double)item.Debe; totalIngreso += (double)item.Debe; Graficas.Add(new ClaseGrafico { Fecha = item.FechaEmision.Value, TipoMovimiento = TipoMovimiento.Ingreso, Monto = (decimal)item.Debe }); } values.Add(new DateModel { DateTime = item.FechaEmision.Value, Value = total }); } SeriesCollection.Add(new LineSeries { Values = values, Title = $"{i.Banco.RazonSocial}" }); Descontado = (decimal)Operaciones.Where(x => x.Descontado != null).Sum(x => x.Descontado); Debe = (decimal)Operaciones.Where(x => x.Debe != null).Sum(x => x.Debe); Haber = (decimal)Operaciones.Where(x => x.Haber != null).Sum(x => x.Haber); Diferencia += Debe - Haber - Descontado; } Cuadros.Add(new CuadroInicio { Titulo = $"Saldo de bancos", Cantidad = $"{Diferencia.ToString("C")}", Icono = MaterialDesignThemes.Wpf.PackIconKind.AccountBalance }); } if (DetalleCaja != null) { var values = new ChartValues <DateModel>(); foreach (var i in DetalleCaja.GroupBy(x => x.CajaId)) { var total = 0d; foreach (var item in i) { if (item.TipoMovimiento == Constantes.TipoMovimiento.Egreso) { total -= (double)item.Monto; Graficas.Add(new ClaseGrafico { Fecha = item.Caja.FechaApertura, TipoMovimiento = TipoMovimiento.Egreso, Monto = (decimal)item.Monto }); } else { total += (double)item.Monto; Graficas.Add(new ClaseGrafico { Fecha = item.Caja.FechaApertura, TipoMovimiento = TipoMovimiento.Ingreso, Monto = (decimal)item.Monto }); } values.Add(new DateModel { DateTime = item.Caja.FechaApertura, Value = total }); } } SeriesCollection.Add(new LineSeries { Values = values, Title = $"Caja" }); } var suma = 0d; var egreso = 0d; foreach (var item in Graficas.OrderBy(x => x.Fecha)) { if (item.TipoMovimiento == Constantes.TipoMovimiento.Egreso) { egreso += (double)item.Monto; egresos.Add(new DateModel { DateTime = item.Fecha.Date, Value = egreso }); } else { suma += (double)item.Monto; cashflow.Add(new DateModel { DateTime = item.Fecha.Date, Value = suma }); } } SeriesCashFlow.Add(new LineSeries { Values = cashflow, Title = $"Ingresos" }); SeriesCashFlow.Add(new LineSeries { Values = egresos, Title = $"Egresos" }); YCashFlow = value => value.ToString("C"); XCashFlow = value => { try { return(new DateTime((long)(value * TimeSpan.FromDays(1).Ticks * 30.44)).ToString("M")); } catch (Exception) { return(DateTime.Now.ToString("M")); } }; YFormatter = value => value.ToString("C"); XFormatter = value => { try { return(new DateTime((long)(value * TimeSpan.FromDays(1).Ticks * 30.44)).ToString("M")); } catch (Exception) { return(DateTime.Now.ToString("M")); } }; if (await ApiProcessor.GetApi <bool>("Caja/CajasEstado")) { var caja = await Servicios.ApiProcessor.GetApi <CajaDto>("Caja/CajaAbierta"); var detallesCaja = new ObservableCollection <DetalleCajaDto>(await Servicios.ApiProcessor.GetApi <DetalleCajaDto[]>($"DetalleCaja/GetByCaja/{caja.Id}")); decimal MontoSistema = 0; if (detallesCaja.Count > 0) { MontoSistema = detallesCaja.Where(x => x.TipoMovimiento == Constantes.TipoMovimiento.Ingreso).Sum(x => x.Monto) - detallesCaja.Where(x => x.TipoMovimiento == Constantes.TipoMovimiento.Egreso).Sum(x => x.Monto); } Cuadros.Add(new CuadroInicio { Titulo = $"Saldo de la caja", Cantidad = $"{MontoSistema.ToString("C")}", Icono = MaterialDesignThemes.Wpf.PackIconKind.CashRegister, Color = "#74D774" }); } else { Cuadros.Add(new CuadroInicio { Titulo = $"La caja esta cerrada", Cantidad = "", Icono = MaterialDesignThemes.Wpf.PackIconKind.CashRegister, Color = "#74D774 " }); } Cuadros.Add(new CuadroInicio { Titulo = $"Gastos de oficina", Cantidad = $"{Oficina.ToString("C")}", Icono = MaterialDesignThemes.Wpf.PackIconKind.Shredder, Color = "#F3E5A1" }); Cuadros.Add(new CuadroInicio { Titulo = $"Cantidad de obras finalizadas", Cantidad = $"{Obras[0]} de {Obras[1]}", Icono = MaterialDesignThemes.Wpf.PackIconKind.TransmissionTower, Color = "#D3B8DD " }); var Gasolina = Jornales.Sum(x => x.Gasolina); var Repuesto = Jornales.Sum(x => x.Repuestos); var Compras = ComprobanteCompras.Where(x => NoObras.Obras.Contains(x.Id)).Sum(x => x.Pagando); Total = Gasolina + Repuesto + Compras; Series.Add(new PieSeries { Title = "Gasolina", Values = new ChartValues <decimal>(new decimal[] { Gasolina }), DataLabels = true, LabelPoint = PointLabel }); Series.Add(new PieSeries { Title = "Repuesto", Values = new ChartValues <decimal>(new decimal[] { Repuesto }), DataLabels = true, LabelPoint = PointLabel }); Series.Add(new PieSeries { Title = "Compras", Values = new ChartValues <decimal>(new decimal[] { Compras }), DataLabels = true, LabelPoint = PointLabel }); SeriesSalida.Add(new PieSeries { Title = "Blanco", Values = new ChartValues <decimal>(new decimal[] { comprobanteSalida[0] }), DataLabels = true, LabelPoint = PointLabel }); SeriesSalida.Add(new PieSeries { Title = "Negro", Values = new ChartValues <decimal>(new decimal[] { comprobanteSalida[1] }), DataLabels = true, LabelPoint = PointLabel }); SeriesEntrada.Add(new PieSeries { Title = "Blanco", Values = new ChartValues <decimal>(new decimal[] { comprobanteEntrada[0] }), DataLabels = true, LabelPoint = PointLabel }); SeriesEntrada.Add(new PieSeries { Title = "Negro", Values = new ChartValues <decimal>(new decimal[] { comprobanteEntrada[1] }), DataLabels = true, LabelPoint = PointLabel }); var Cobrado = Presupuestos.Sum(x => x.CobradoSinImpuestos); TotalPresupuesto = Presupuestos.Sum(x => x.TotalSinImpuestos); var DiferenciaPresupuesto = TotalPresupuesto - Cobrado; SeriesPresupuesto.Add(new PieSeries { Title = "Cobrado", Values = new ChartValues <decimal>(new decimal[] { Cobrado }), DataLabels = true, LabelPoint = PointLabelPresupuesto }); SeriesPresupuesto.Add(new PieSeries { Title = "Faltante", Values = new ChartValues <decimal>(new decimal[] { DiferenciaPresupuesto }), DataLabels = true, LabelPoint = PointLabelPresupuesto }); } catch (Exception) { MessageBox.Show("No se pudo cargar por problemas de conexion."); } }
private void ShowOnHistogram(bool isInputImage) { List <int[]> histogram = HistogramGenerator.Generate(isInputImage ? input : output); SolidColorBrush redColor, greenColor, blueColor; string redTitle, greenTitle, blueTitle; if (ImageHelper.GetBitsPerPixel(isInputImage ? input.PixelFormat : output.PixelFormat) > 8) { redColor = System.Windows.Media.Brushes.Red; greenColor = System.Windows.Media.Brushes.Green; blueColor = System.Windows.Media.Brushes.Blue; redTitle = "Red"; greenTitle = "Green"; blueTitle = "Blue"; } else { redColor = System.Windows.Media.Brushes.Gray; greenColor = System.Windows.Media.Brushes.Gray; blueColor = System.Windows.Media.Brushes.Gray; redTitle = "Gray"; greenTitle = "Gray"; blueTitle = "Gray"; } SeriesCollection red = new SeriesCollection { new ColumnSeries { Title = redTitle, Values = new ChartValues <double> { }, ColumnPadding = 0, Fill = redColor } }; SeriesCollection green = new SeriesCollection { new ColumnSeries { Title = greenTitle, Values = new ChartValues <double> { }, ColumnPadding = 0, Fill = greenColor } }; SeriesCollection blue = new SeriesCollection { new ColumnSeries { Title = blueTitle, Values = new ChartValues <double> { }, ColumnPadding = 0, Fill = blueColor } }; for (int i = 0; i < histogram[0].Length; i++) { red[0].Values.Add((double)histogram[0][i]); green[0].Values.Add((double)histogram[1][i]); blue[0].Values.Add((double)histogram[2][i]); } if (isInputImage) { ChartsUserControl.InputRed = red; ChartsUserControl.InputGreen = green; ChartsUserControl.InputBlue = blue; } else { ChartsUserControl.OutputRed = red; ChartsUserControl.OutputGreen = green; ChartsUserControl.OutputBlue = blue; } }
public LabChart(IPpnRepo ppnRepo, string nutrientName, double nutrientValue, string horseName, List <NutrientBulletPoint> bulletPoints) { _ppnRepo = ppnRepo; var nutrientAverage = _ppnRepo.NutrientAverage(nutrientName); var nutrientTolerances = _ppnRepo.HighLowTolerance(nutrientAverage); Nutrient = nutrientName; SeriesCollection = new SeriesCollection { new ColumnSeries { Title = horseName, Values = new ChartValues <double> { Math.Round(nutrientValue, 2) }, FontFamily = new FontFamily("./Fonts/#Open Sans Condensed Light"), DataLabels = true }, new ColumnSeries { Title = "All Horses Average", Values = new ChartValues <double> { Math.Round(nutrientAverage, 2) }, FontFamily = new FontFamily("./Fonts/#Open Sans Condensed Light"), DataLabels = true } }; DataContext = this; NutrientName = nutrientName; if (bulletPoints.Any() && bulletPoints[0].Range == "Heavy Metal") { BulletPoints = bulletPoints; } else if (nutrientValue > nutrientTolerances.HighTolerance) { BulletPoints = bulletPoints.Where(bp => bp.Range == "Excessive").ToList(); } else if (nutrientValue < nutrientTolerances.LowTolerance) { BulletPoints = bulletPoints.Where(bp => bp.Range == "Deficient").ToList(); } else { BulletPoints = new List <NutrientBulletPoint> { new NutrientBulletPoint { NutrientName = nutrientName, BulletPoint = $"{nutrientName} is within tolerance" } } }; Formatter = value => Math.Round(value, 2).ToString(); //Labels = new string[] { nutrientValue.ToString(), Math.Round(nutrientAverage,0).ToString() }; InitializeComponent(); if (nutrientValue != 0 && nutrientAverage != 0) { NutrientChart.AxisY.Clear(); NutrientChart.AxisY.Add( new Axis { Separator = new LiveCharts.Wpf.Separator { Step = nutrientAverage > nutrientValue ? nutrientAverage * 0.30 : nutrientValue * 0.30 }, LabelFormatter = Formatter } ); } }
public ScheduleChartViewModel() { SeriesCollection = new SeriesCollection(); }
public Dashboard() { InitializeComponent(); SeriesCollection = new SeriesCollection { new PieSeries { Title = "Śniadanie", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, new PieSeries { Title = "II Śniadanie", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, new PieSeries { Title = "Obiad", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, new PieSeries { Title = "Podwieczorek", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, new PieSeries { Title = "Kolacja", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, }; EnergiaCollection = new SeriesCollection { new PieSeries { Title = "Białko", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, new PieSeries { Title = "Tłuszcze", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, new PieSeries { Title = "Węglowodany przyswajalne", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false }, new PieSeries { Title = "Inne", Values = new ChartValues <ObservableValue> { new ObservableValue(0) }, DataLabels = false } }; DataContext = this; ListaProduktow = DAO.ProductsDAO.SelectAll().OrderBy(x => x.nazwa).ToList(); produkty.ItemsSource = ListaProduktow.Select(x => x.nazwa); miasto.ItemsSource = DAO.UnitsDAO.SelectAll().Select(x => x.miasto); posilki.SelectedIndex = Properties.Settings.Default.recepie_tab; miasto.SelectedIndex = Properties.Settings.Default.dashboard_unit; dieta.SelectedIndex = Properties.Settings.Default.dashboard_diet; kategoria.SelectedIndex = Properties.Settings.Default.dashboard_kategoria; if (Properties.Settings.Default.dashboard_date == new DateTime(2000, 1, 1)) { data.SelectedDate = DateTime.Now; } else { data.SelectedDate = Properties.Settings.Default.dashboard_date; } nazwa_sniadanie.Text = Properties.Settings.Default.dashboard_nazwa_sniadanie; nazwa_IIsniadanie.Text = Properties.Settings.Default.dashboard_nazwa_IIsniadanie; nazwa_obiad.Text = Properties.Settings.Default.dashboard_nazwa_obiad; nazwa_podwieczorek.Text = Properties.Settings.Default.dashboard_nazwa_podwieczorek; nazwa_kolacja.Text = Properties.Settings.Default.dashboard_nazwa_kolacja; LoadMenu(); LiczSrednia(); }
public void Refresh() { PieSeries = new SeriesCollection(); PieSeries.AddRange(Series); }
private void init() { var ls = new LineSeries { AreaLimit = -10, Values = new ChartValues <ObservableValue> { new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0), new ObservableValue(0) } }; ls.Foreground = Brushes.Pink; ls.Stroke = Brushes.Pink; ls.LineSmoothness = 1; ls.PointGeometrySize = 0; ls.Fill = Brushes.Transparent; LastHourSeries = new SeriesCollection { ls }; NetworkChart.Series = LastHourSeries; NetworkChart.AxisY.Clear(); NetworkChart.AxisY.Add(new Axis { LabelFormatter = value => { var tt = (int)value; if (tt == 0) { return("0 KB"); } if (tt < 1024) { return(value.ToString("#,#") + " KB"); } else { return((value / 1024).ToString("#,#") + " MB"); } }, Separator = new LiveCharts.Wpf.Separator(), MinValue = 0, }); }
private void ShowColumnGraph(SeriesCollection columnseries) { cartesianChart2.AxisX.Clear(); cartesianChart2.AxisY.Clear(); DateTime now = DateTime.Now; var columnlabels = new List <string>(); cartesianChart2.AxisX.Add(new LiveCharts.Wpf.Axis { Title = "", Labels = columnlabels }); cartesianChart2.AxisY.Add(new Axis { Title = "Total Speaking Time[s]" //LabelFormatter = value => value.ToString(), }); cartesianChart2.AxisY[0].MinValue = 0; cartesianChart2.LegendLocation = LiveCharts.LegendLocation.Right; using (WorkshopEntities7 db = new WorkshopEntities7()) { if (selectedgroup == "Adults") { var data = db.Adults; var users = (from o in data orderby o.username select o.username).Distinct(); foreach (var user in users) { columnlabels.Add(user.ToString()); } } else if (selectedgroup == "Students") { var data = db.Students; var users = (from o in data orderby o.username select o.username).Distinct(); foreach (var user in users) { columnlabels.Add(user.ToString()); } } else { var data = db.voicerecords; var users = (from o in data orderby o.username select o.username).Distinct(); foreach (var user in users) { columnlabels.Add(user.ToString()); } } } cartesianChart2.Series = columnseries; //using (TestEntities1 db = new TestEntities1()) using (WorkshopEntities7 db = new WorkshopEntities7()) {/* * var data = db.voicerecords; * var users = (from o in data orderby o.username select o.username).Distinct(); * * * ColumnSeries column = new ColumnSeries() * { * Title = now.AddMinutes(-chartRangeMinute).ToShortTimeString() + "~" + now.AddMinutes(-chartRangeMinute / 2).ToShortTimeString(), * * DataLabels = false, * Values = new ChartValues<double>(), * * }; * ColumnSeries column2 = new ColumnSeries() * { * Title = now.AddMinutes(-chartRangeMinute / 2).ToShortTimeString() + "~" + now.ToShortTimeString(), * * DataLabels = false, * Values = new ChartValues<double>(), * * }; * * * foreach (var user in users) * { * * columnlabels.Add(user.ToString()); * * double totalseconds1 = 5; * double totalseconds2 = 5; * * for (DateTime itime = now.AddMinutes(-chartRangeMinute); itime < now; itime = itime.AddMinutes(1)) * { * double v1 = 0; * var ruleDate = Convert.ToDateTime(itime).TimeOfDay; * * var userdatas = from oo in data * where SqlFunctions.DatePart("minute", oo.Date) == SqlFunctions.DatePart("minute", itime) * && oo.username.Equals(user) * && SqlFunctions.DatePart("hour", oo.Date) == SqlFunctions.DatePart("hour", itime) * && oo.time < 60 * select oo.time; * * if (userdatas.FirstOrDefault() != null) //changed from SingleOrDefault * { * v1 = (double)userdatas.FirstOrDefault(); * * } * * if (itime.TimeOfDay < now.AddMinutes(-chartRangeMinute/2).TimeOfDay) * { * totalseconds1 = totalseconds1 + v1; * } * else * { * totalseconds2 = totalseconds2 + v1; * } * Console.WriteLine(itime); * * } * * column.Values.Add(totalseconds1); * column2.Values.Add(totalseconds2); * * } * columnseries.Add(column); * columnseries.Add(column2); * */ } }
private void displayChart() { int numPoints = (int)this.ActualWidth / 2; var xValues = ViewModel.GetTimeSeries(numPoints); var maxHeartRate = ViewModel.MaxHeartRate; var maxSpeed = ViewModel.MaxSpeedKmH; var maxCadence = ViewModel.MaxCadence; var maxElevation = ViewModel.MaxElevation; var maxStrideLength = ViewModel.MaxStrideLengthM; TimeChart.AxisY.Clear(); bool showAnySpeed = ViewModel.DoShowSpeed || ViewModel.DoShowTargetSpeed; bool showAnyHeartRate = ViewModel.DoShowHeartRate; bool showAnyPace = ViewModel.DoShowPace || ViewModel.DoShowTargetPace; bool showAnyElevation = ViewModel.DoShowElevation || ViewModel.DoShowElevationChange; bool showAnyCadence = ViewModel.DoShowCadence; bool showAnyStrideLength = ViewModel.DoShowStrideLength; int speedAxisIndex = -1; int heartRateAxisIndex = -1; int paceAxisIndex = -1; int elevationAxisIndex = -1; int cadenceAxisIndex = -1; int strideLengthAxisIndex = -1; if (showAnySpeed) { var speedAxis = new Axis() { Title = "Speed", Foreground = System.Windows.Media.Brushes.DodgerBlue, LabelFormatter = value => { return(value.ToString("0.0")); } }; speedAxisIndex = TimeChart.AxisY.Count; TimeChart.AxisY.Add(speedAxis); } if (showAnyHeartRate) { var heartRateAxis = new Axis() { Title = "HeartRate (bpm)", Foreground = System.Windows.Media.Brushes.IndianRed, LabelFormatter = value => { return(value.ToString("0")); }, Position = AxisPosition.RightTop }; heartRateAxisIndex = TimeChart.AxisY.Count; TimeChart.AxisY.Add(heartRateAxis); } if (showAnyPace) { var paceAxis = new Axis() { Title = "Pace (min/km)", Foreground = System.Windows.Media.Brushes.DarkOliveGreen, LabelFormatter = value => new Pace(value).ToString(), }; paceAxisIndex = TimeChart.AxisY.Count; TimeChart.AxisY.Add(paceAxis); } if (showAnyElevation) { var elevationAxis = new Axis() { Title = "Elevation (m)", Foreground = System.Windows.Media.Brushes.Black, LabelFormatter = value => value.ToString("0"), Position = AxisPosition.RightTop }; elevationAxisIndex = TimeChart.AxisY.Count; TimeChart.AxisY.Add(elevationAxis); } if (showAnyCadence) { var cadenceAxis = new Axis() { Title = "Cadence (steps/min)", Foreground = System.Windows.Media.Brushes.Magenta, LabelFormatter = value => value.ToString("0"), Position = AxisPosition.RightTop }; cadenceAxisIndex = TimeChart.AxisY.Count; TimeChart.AxisY.Add(cadenceAxis); } if (showAnyStrideLength) { var strideLength = new Axis() { Title = "StrideLength (m)", Foreground = System.Windows.Media.Brushes.Teal, LabelFormatter = value => value.ToString("0.0"), Position = AxisPosition.RightTop }; strideLengthAxisIndex = TimeChart.AxisY.Count; TimeChart.AxisY.Add(strideLength); } var seriesCollection = new SeriesCollection(); TimeChart.Series.Clear(); if (ViewModel.DoShowSpeed) { var speeds = ViewModel.GetTimeLine <double>(nameof(TrackPoint.SpeedKmH), numPoints); var series = new LineSeries { Title = "Speed", Values = new ChartValues <double>(speeds), PointGeometry = null, Fill = Brushes.Transparent, LineSmoothness = 1, Stroke = TimeChart.AxisY[speedAxisIndex].Foreground, ScalesYAt = speedAxisIndex }; seriesCollection.Add(series); } if (ViewModel.DoShowPace) { var speeds = ViewModel.GetTimeLine <double>(nameof(TrackPoint.SpeedKmH), numPoints); var series = new LineSeries { Title = "Pace", Values = new ChartValues <double>(speeds), PointGeometry = null, Fill = Brushes.Transparent, LineSmoothness = 1, LabelPoint = chartPoint => $"{new Pace(chartPoint.Y).ToString()}min/km", Stroke = TimeChart.AxisY[paceAxisIndex].Foreground, ScalesYAt = paceAxisIndex }; seriesCollection.Add(series); } if (ViewModel.DoShowHeartRate) { var heartRates = ViewModel.GetTimeLine <int>(nameof(TrackPoint.HeartRateBpm), numPoints).Select(hr => ((double)hr)).ToList(); var series = new LineSeries { Title = "HeartRate", Values = new ChartValues <double>(heartRates), PointGeometry = null, Fill = Brushes.Transparent, LineSmoothness = 0, LabelPoint = chartPoint => $"{chartPoint.Y.ToString("0")}bpm", Stroke = TimeChart.AxisY[heartRateAxisIndex].Foreground, ScalesYAt = heartRateAxisIndex }; seriesCollection.Add(series); } if (ViewModel.DoShowTargetSpeed) { var targetSpeeds = ViewModel.GetTimeLine <double>(nameof(LapViewModel.TargetSpeed), numPoints); var series = new StepLineSeries { Title = "Target Speed", Fill = Brushes.Transparent, Values = new ChartValues <double>(targetSpeeds), PointGeometry = null, AlternativeStroke = Brushes.Transparent, Stroke = TimeChart.AxisY[speedAxisIndex].Foreground.Clone(), ScalesYAt = speedAxisIndex }; series.Stroke.Opacity = 0.7; seriesCollection.Add(series); } if (ViewModel.DoShowTargetPace) { var targetSpeeds = ViewModel.GetTimeLine <double>(nameof(LapViewModel.TargetSpeed), numPoints); var series = new StepLineSeries { Title = "Target Pace", Fill = Brushes.Transparent, Values = new ChartValues <double>(targetSpeeds), PointGeometry = null, AlternativeStroke = Brushes.Transparent, LabelPoint = chartPoint => $"{new Pace(chartPoint.Y).ToString()}min/km", Stroke = TimeChart.AxisY[paceAxisIndex].Foreground.Clone(), ScalesYAt = paceAxisIndex }; series.Stroke.Opacity = 0.7; seriesCollection.Add(series); } if (ViewModel.DoShowCadence) { if (maxCadence > 0) { var cadences = ViewModel.GetTimeLine <double>(nameof(TrackPoint.RunCadence), numPoints); cadences = cadences.Select(c => c * 2).ToList(); var series = new LineSeries { Title = "Cadence", Values = new ChartValues <double>(cadences), PointGeometry = null, Fill = Brushes.Transparent, LineSmoothness = 0, LabelPoint = chartPoint => $"{chartPoint.Y.ToString("0")} steps/min", Stroke = TimeChart.AxisY[cadenceAxisIndex].Foreground, ScalesYAt = cadenceAxisIndex }; seriesCollection.Add(series); } } if (ViewModel.DoShowStrideLength) { if (maxStrideLength > 0) { var strideLengths = ViewModel.GetTimeLine <double>(nameof(TrackPoint.StrideLengthM), numPoints); var series = new LineSeries { Title = "StrideLength", Values = new ChartValues <double>(strideLengths), PointGeometry = null, Fill = Brushes.Transparent, LineSmoothness = 0, LabelPoint = chartPoint => $"{chartPoint.Y.ToString("0.0")} m", Stroke = TimeChart.AxisY[strideLengthAxisIndex].Foreground, ScalesYAt = strideLengthAxisIndex }; seriesCollection.Add(series); } } if (ViewModel.DoShowElevation) { if (maxElevation > 0) { var elevations = ViewModel.GetTimeLine <double>(nameof(TrackPoint.AltitudeMeters), numPoints); var series = new LineSeries { Title = "Elevation", Values = new ChartValues <double>(elevations), PointGeometry = null, Fill = Brushes.Transparent, LineSmoothness = 0, LabelPoint = chartPoint => $"{chartPoint.Y.ToString("0.0")} m", Stroke = TimeChart.AxisY[elevationAxisIndex].Foreground, ScalesYAt = elevationAxisIndex }; seriesCollection.Add(series); } } if (ViewModel.DoShowElevationChange && ViewModel.Laps.SelectMany(l => l.TrackPoints).Any()) { if (maxElevation > 0 && maxSpeed > 0) { var elevations = ViewModel.GetTimeLine <double>(nameof(TrackPoint.AltitudeMeters), numPoints).ToList(); var elevationChanges = new List <Double>(); elevationChanges.Add(0); for (int i = 1; i < elevations.Count; i++) { elevationChanges.Add(elevations[i] - elevations[i - 1]); } var maxChange = elevationChanges.Max(); var minChange = elevationChanges.Min(); var totalChangeExtent = maxChange - minChange; if (totalChangeExtent > 0) { var series = new LineSeries { Title = "Elevation Change", Values = new ChartValues <double>(elevationChanges), PointGeometry = null, Fill = Brushes.Transparent, LineSmoothness = 0, LabelPoint = chartPoint => $"{chartPoint.Y} m", Stroke = TimeChart.AxisY[elevationAxisIndex].Foreground.Clone(), ScalesYAt = elevationAxisIndex }; series.Stroke.Opacity = 0.7; seriesCollection.Add(series); } } } TimeChart.Series.AddRange(seriesCollection); TimeChart.AxisX.Clear(); var timeAxis = new Axis() { Labels = xValues.Select(b => b.ToString()).ToArray() }; TimeChart.AxisX.Add(timeAxis); TimeChart.Zoom = ZoomingOptions.X; }
private void Member_Loaded(object sender, RoutedEventArgs e) { if (loaded) { return; } loaded = true; var type = new string[] { "메시지", "", "들어옴", "나감", "오류" }; var talklistdc = TalkList.DataContext as TalkListViewModel; foreach (var talk in TalkInstance.Instance.Manager.Members[id].Talks) { talklistdc.Items.Add(new TalkListItemViewModel { 인덱스 = talk.Index.ToString(), 형 = type[(int)talk.State], 내용 = talk.Content ?? "", 작성자 = talk.State == TalkState.Append ? "" : talk.Name ?? "", 날짜 = talk.State != TalkState.Append && talk.Time != new DateTime() ? talk.Time.ToString() : "", Talk = talk }); } var Series = new SeriesCollection(); var week = new int[7]; foreach (var talk in TalkInstance.Instance.Manager.Members[id].Talks) { if (talk.State == TalkState.Message) { week[(int)talk.Time.DayOfWeek]++; } } Series.Add(new LineSeries { Title = "", Values = new ChartValues <int>(week), Fill = new SolidColorBrush { Color = Colors.Pink, Opacity = .4 }, Stroke = Brushes.Pink, LineSmoothness = 0.7, PointGeometrySize = 10, }); Labels = "일월화수목금토".Select(x => x.ToString()).ToArray(); WeeklyChart.Series = Series; var Series2 = new SeriesCollection(); var day = new int[24]; foreach (var talk in TalkInstance.Instance.Manager.Members[id].Talks) { if (talk.State == TalkState.Message) { day[talk.Time.Hour]++; } } Series2.Add(new LineSeries { Title = "", Values = new ChartValues <int>(day), Fill = new SolidColorBrush { Color = Colors.Pink, Opacity = .4 }, Stroke = Brushes.Pink, LineSmoothness = 0.7, PointGeometrySize = 10, }); Labels2 = Enumerable.Range(0, 24).Select(x => x.ToString()).ToArray(); DailyChart.Series = Series2; DataContext = this; Task.Run(() => { var name = TalkInstance.Instance.Manager.Members[id].Name; TalkInstance.Instance.Manager.StartSpecificMessageAnalyze(x => x.Name == name, x => { }, true, false, false, false); var ll = TalkInstance.Instance.Manager.Words.ToList(); ll.Sort((x, y) => y.Value.CompareTo(x.Value)); if (ll.Count > 5) { ll.RemoveRange(5, ll.Count - 5); } Extends.Post(() => { KeywordCharts.Series = new SeriesCollection(); KeywordCharts.Series.AddRange(ll.Select(x => { return(new PieSeries { Title = "", //x.Key, Values = new ChartValues <int>(new int[] { x.Value }), DataLabels = true, LabelPoint = y => x.Key, }); })); Progress.Visibility = Visibility.Collapsed; KeywordCharts.Visibility = Visibility.Visible; }); }); }
public MainWindow() { InitializeComponent(); timer.Start(); setUpBaudRates(); var config = new SeriesConfiguration <tempGraph>(); config.Y(model => model.temperature); config.X(model => model.time.ToOADate()); Series = new SeriesCollection(config) { new LineSeries { Values = new ChartValues <tempGraph>() } }; Series.Add(new LineSeries { Values = new ChartValues <tempGraph>() }); Series.Add(new LineSeries { Values = new ChartValues <tempGraph>() }); Series[0].Title = "External Temperature"; Series[1].Title = "Internal Temperature"; Series[2].Title = "Ground Temperature"; XFormatter = val => DateTime.FromOADate(val).ToString("mm.ss"); YFormatter = val => val + " °"; DataContext = this; _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) }; _timer.Tick += TimerOnTick; _timer.Start(); var config2 = new SeriesConfiguration <pressureGraph>(); config2.Y(model => model.pressure); config2.X(model => model.time.ToOADate()); Series2 = new SeriesCollection(config2) { new LineSeries { Values = new ChartValues <pressureGraph>() } }; Series2.Add(new LineSeries { Values = new ChartValues <pressureGraph>() }); Series2[0].Title = "Barometric Pressure"; Series2[1].Title = "Ground Barometric Pressure"; XFormatter2 = val => DateTime.FromOADate(val).ToString("mm.ss"); YFormatter2 = val => val + "hPa"; DataContext = this; _timer2 = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) }; _timer2.Tick += Timer2OnTick; _timer2.Start(); this.Show(); setUpPossibleInputsForSerialPort(); ///AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Binding binding_1 = new Binding("SelectedValue"); binding_1.Source = VideoDevicesComboBox; WebcamCtrl.SetBinding(Webcam.VideoDeviceProperty, binding_1); Binding binding_2 = new Binding("SelectedValue"); binding_2.Source = AudioDevicesComboBox; WebcamCtrl.SetBinding(Webcam.AudioDeviceProperty, binding_2); // Create directory for saving video files string videoPath = @"C:\VideoClips"; if (!Directory.Exists(videoPath)) { Directory.CreateDirectory(videoPath); } // Create directory for saving image files string imagePath = @"C:\WebcamSnapshots"; if (!Directory.Exists(imagePath)) { Directory.CreateDirectory(imagePath); } //AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA // Set some properties of the Webcam control WebcamCtrl.VideoDirectory = videoPath; WebcamCtrl.ImageDirectory = imagePath; WebcamCtrl.FrameRate = 72; WebcamCtrl.FrameSize = new System.Drawing.Size(1080, 720); // Find available a/v devices var vidDevices = EncoderDevices.FindDevices(EncoderDeviceType.Video); var audDevices = EncoderDevices.FindDevices(EncoderDeviceType.Audio); VideoDevicesComboBox.ItemsSource = vidDevices; AudioDevicesComboBox.ItemsSource = audDevices; VideoDevicesComboBox.SelectedIndex = 0; AudioDevicesComboBox.SelectedIndex = 0; releaseServo.IsEnabled = false; servoArm.IsEnabled = false; t1.IsEnabled = false; t2.IsEnabled = false; bw.DoWork += Bw_DoWork; bw.RunWorkerCompleted += Bw_RunWorkerCompleted; bw.RunWorkerAsync(); }
/// <summary> /// Refreshes the UI. /// </summary> /// <param name="currentTGData">The current tg data.</param> private void RefreshUI(TGData currentTGData) { this.Dispatcher.Invoke(() => { try { // Gauge Signal Quality // هر هنگام که اطلاعات جدیدی بیاید مقدار را به روزآوری می کنیم if (currentTGData.PoorSignal != -1) { var SignalQuality = Math.Round((200D - currentTGData.PoorSignal) / 2D, 1); if (SignalQuality < 0) { SignalQuality = 0; } GaugeSignal.Value = SignalQuality; TGLatestData.PoorSignal = currentTGData.PoorSignal; } // Gauge ATTENTION/MEDITATION if (currentTGData.Attention != -1) { GaugeAttention.Value = TGLatestData.Attention = currentTGData.Attention; } if (currentTGData.Meditation != -1) { GaugeMeditation.Value = TGLatestData.Meditation = currentTGData.Meditation; } // AngularGauges: BlinkStrength if (currentTGData.BlinkStrength != -1) { GaugeBlinkStrength.Value = (currentTGData.BlinkStrength / 255D * 100D); GaugeBlinkStrength.Tag = _RESET_WAITING_STEPS; TGLatestData.BlinkStrength = currentTGData.BlinkStrength; } if (GaugeBlinkStrength.Tag != null) { var CleanTime = (int)GaugeBlinkStrength.Tag - 1; if (CleanTime == 0) { GaugeBlinkStrength.Tag = null; GaugeBlinkStrength.Value = 0; GaugeBlinkStrength.NeedleFill = Brushes.Black; } else { GaugeBlinkStrength.Tag = CleanTime; GaugeBlinkStrength.NeedleFill = Brushes.Gold; } } // AngularGauges: TaskFamiliarity if (currentTGData.TaskFamiliarity != 0) { GaugeTaskFamiliarity.Value = currentTGData.TaskFamiliarity; GaugeTaskFamiliarity.Tag = _RESET_WAITING_STEPS; TGLatestData.TaskFamiliarity = currentTGData.TaskFamiliarity; } if (GaugeTaskFamiliarity.Tag != null) { var CleanTime = (int)GaugeTaskFamiliarity.Tag - 1; if (CleanTime == 0) { GaugeTaskFamiliarity.Tag = null; GaugeTaskFamiliarity.Value = 0; GaugeTaskFamiliarity.NeedleFill = Brushes.Black; } else { GaugeTaskFamiliarity.Tag = CleanTime; GaugeTaskFamiliarity.NeedleFill = Brushes.Gold; } } // AngularGauges: MentalEffort if (currentTGData.MentalEffort != 0) { GaugeMentalEffort.Value = currentTGData.MentalEffort; GaugeMentalEffort.Tag = _RESET_WAITING_STEPS; TGLatestData.MentalEffort = currentTGData.MentalEffort; } if (GaugeMentalEffort.Tag != null) { var CleanTime = (int)GaugeMentalEffort.Tag - 1; if (CleanTime == 0) { GaugeMentalEffort.Tag = null; GaugeMentalEffort.Value = 0; GaugeMentalEffort.NeedleFill = Brushes.Black; } else { GaugeMentalEffort.Tag = CleanTime; GaugeMentalEffort.NeedleFill = Brushes.Gold; } } // Chart Data / EEG Data // اطلاعات را ابتدا تبدیل به ساختارهای مناسب برای چارت کرده و سپس آن را یکجا به روزآوری می کنیم if (currentTGData.EegPowerDelta != 0) { var ListLineSeries = new List <LineSeries>(); ListLineSeries.Add(new LineSeries() { Title = "Delta Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerDelta).ToArray()), PointGeometry = null, }); ListLineSeries.Add(new LineSeries() { Title = "Theta Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerTheta).ToArray()), PointGeometry = null, }); ListLineSeries.Add(new LineSeries() { Title = "Low Alpha Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerAlpha1).ToArray()), PointGeometry = null, }); ListLineSeries.Add(new LineSeries() { Title = "High Alpha Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerAlpha2).ToArray()), PointGeometry = null, }); ListLineSeries.Add(new LineSeries() { Title = "Low Beta Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerBeta1).ToArray()), PointGeometry = null, }); ListLineSeries.Add(new LineSeries() { Title = "High Beta Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerBeta2).ToArray()), PointGeometry = null, }); ListLineSeries.Add(new LineSeries() { Title = "Low Gamma Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerGamma1).ToArray()), PointGeometry = null, }); ListLineSeries.Add(new LineSeries() { Title = "High Gamma Power", Values = new ChartValues <double>(TGQueue.Select(q => q.EegPowerGamma2).ToArray()), PointGeometry = null, }); var TGChartSeriesCollection = new SeriesCollection(); TGChartSeriesCollection.AddRange(ListLineSeries); this.CartesianChartWaves.AxisX[0].Labels = TGQueue.Select(q => q.TimeStamp.ToString()).ToArray(); this.CartesianChartWaves.AxisY[0].LabelFormatter = value => value.ToString("N0"); this.CartesianChartWaves.Series = TGChartSeriesCollection; // به روزآوری اطلاعات TGLatestData.EegPowerDelta = currentTGData.EegPowerDelta; TGLatestData.EegPowerTheta = currentTGData.EegPowerTheta; TGLatestData.EegPowerAlpha1 = currentTGData.EegPowerAlpha1; TGLatestData.EegPowerAlpha2 = currentTGData.EegPowerAlpha2; TGLatestData.EegPowerBeta1 = currentTGData.EegPowerBeta1; TGLatestData.EegPowerBeta2 = currentTGData.EegPowerBeta2; TGLatestData.EegPowerGamma1 = currentTGData.EegPowerGamma1; TGLatestData.EegPowerGamma2 = currentTGData.EegPowerGamma2; } // اطلاعاتی که در مورد اقدامی انجام نشده است if (currentTGData.TaskDifficulty != 0) { TGLatestData.TaskDifficulty = currentTGData.TaskDifficulty; } if (currentTGData.RawCh1 != 0) { TGLatestData.RawCh1 = currentTGData.RawCh1; } if (currentTGData.RawCh2 != 0) { TGLatestData.RawCh2 = currentTGData.RawCh2; } if (currentTGData.RawCh3 != 0) { TGLatestData.RawCh3 = currentTGData.RawCh3; } if (currentTGData.RawCh4 != 0) { TGLatestData.RawCh4 = currentTGData.RawCh4; } if (currentTGData.RawCh5 != 0) { TGLatestData.RawCh5 = currentTGData.RawCh5; } if (currentTGData.RawCh6 != 0) { TGLatestData.RawCh6 = currentTGData.RawCh6; } if (currentTGData.RawCh7 != 0) { TGLatestData.RawCh7 = currentTGData.RawCh7; } if (currentTGData.RawCh8 != 0) { TGLatestData.RawCh8 = currentTGData.RawCh8; } if (currentTGData.MSG_ERR_CFG_OVERRIDE != 0) { TGLatestData.MSG_ERR_CFG_OVERRIDE = currentTGData.MSG_ERR_CFG_OVERRIDE; } if (currentTGData.MSG_ERR_NOT_PROVISIONED != 0) { TGLatestData.MSG_ERR_NOT_PROVISIONED = currentTGData.MSG_ERR_NOT_PROVISIONED; } if (currentTGData.MSG_MODEL_IDENTIFIED != 0) { TGLatestData.MSG_MODEL_IDENTIFIED = currentTGData.MSG_MODEL_IDENTIFIED; } if (currentTGData.RespiratoryRate != 0) { TGLatestData.RespiratoryRate = currentTGData.TaskDifficulty; } if (currentTGData.Positivity) { TGLatestData.Positivity = currentTGData.Positivity; } // Update TextLog | نمایش متنی var TextLog = new StringBuilder(); TextLog.AppendLine("آخرین اطلاعات دریافتی"); typeof(TGData).GetProperties().ToList().ForEach(p => TextLog.AppendLine($"{p.Name}: {(p.GetValue(this.TGLatestData)?.ToString() ?? "null")}")); this.TextBlockLog.Text = TextLog.ToString(); } catch (Exception ex) { this.LogAdd("Exception: RefreshUI"); this.LogAdd(ex.Message); } }, DispatcherPriority.ContextIdle); }
public void getPengirimanDiagram() { // CARTESIAN CHART // setting up the x axis and y axis cartesianChart1.AxisX.Add(new LiveCharts.Wpf.Axis { Title = tabelPengiriman.Columns[1].Name, Labels = new[] { "Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des" } }); cartesianChart1.AxisY.Add(new LiveCharts.Wpf.Axis { Title = "Frekuensi", LabelFormatter = value => value.ToString() }); cartesianChart1.LegendLocation = LiveCharts.LegendLocation.Right; // setting up the data that will be visualized through line cartesianChart1.Series.Clear(); SeriesCollection series = new SeriesCollection(); try { conn.Open(); NpgsqlDataReader myReader = cmd.ExecuteReader(); // select distinct year (year is represented by line) List <string> yearsList = new List <string>(); while (myReader.Read()) { yearsList.Add(myReader["tahun"].ToString()); } var years = yearsList.Distinct(); // create dot based on monthly frequency foreach (var year in years) { List <double> frekuensiList = new List <double>(); for (int month = 1; month <= 12; month++) { double frekuensi = 0; DataRow[] result = dt.Select("tahun = " + year + " AND bulan = " + month); foreach (DataRow row in result) { frekuensi = Double.Parse(row[2].ToString()); } frekuensiList.Add(frekuensi); } series.Add(new LineSeries() { Title = year.ToString(), Values = new ChartValues <double>(frekuensiList) }); } cartesianChart1.Series = series; conn.Close(); } catch (NpgsqlException ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Sorts the given <see cref="SeriesCollection"/>. /// </summary> /// <param name="series"></param> protected virtual void SortSeries(SeriesCollection series) { series.Sort(GetSeriesComparer()); }
//category chart init public void ScategoryBookInit() { string query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Science Fiction'"; SqlCeCommand cmd = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int scienceFCount = (int)cmd.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Drama'"; SqlCeCommand cmd2 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int dramaCount = (int)cmd2.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Action/Adventure'"; SqlCeCommand cmd3 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int acAdvCount = (int)cmd3.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Romance'"; SqlCeCommand cmd4 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int romanceCount = (int)cmd4.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Mystery'"; SqlCeCommand cmd5 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int mysteryCount = (int)cmd5.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Fantasy'"; SqlCeCommand cmd6 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int fantasyCount = (int)cmd6.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Biographies'"; SqlCeCommand cmd7 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int biographyCount = (int)cmd7.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Trilogy'"; SqlCeCommand cmd8 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int trilogyCount = (int)cmd8.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Series'"; SqlCeCommand cmd9 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int seriesCount = (int)cmd9.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Journals'"; SqlCeCommand cmd10 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int journCount = (int)cmd10.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Diaries'"; SqlCeCommand cmd11 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int diaryCount = (int)cmd11.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Cookbooks'"; SqlCeCommand cmd12 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int cookCount = (int)cmd12.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Art'"; SqlCeCommand cmd13 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int ArtCount = (int)cmd13.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Comics'"; SqlCeCommand cmd14 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int ComicCount = (int)cmd14.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Dictionaries'"; SqlCeCommand cmd15 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int dictioCount = (int)cmd15.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Encyclopedias'"; SqlCeCommand cmd16 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int encycloCount = (int)cmd16.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Math'"; SqlCeCommand cmd17 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int mathCount = (int)cmd17.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Religion'"; SqlCeCommand cmd18 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int religionCount = (int)cmd18.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Science'"; SqlCeCommand cmd19 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int ScienceCount = (int)cmd19.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Health'"; SqlCeCommand cmd20 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int healthCount = (int)cmd20.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'History'"; SqlCeCommand cmd21 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int historyCount = (int)cmd21.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Self help'"; SqlCeCommand cmd22 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int sHelpCount = (int)cmd22.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM SBooks WHERE [Genre] = 'Poetry'"; SqlCeCommand cmd23 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int peotryCount = (int)cmd23.ExecuteScalar(); databaseConnection.Close(); SeriesCollection1 = new SeriesCollection { new ColumnSeries { Title = "Genre", Values = new ChartValues <double> { scienceFCount, dramaCount, acAdvCount, romanceCount, mysteryCount, fantasyCount, biographyCount, trilogyCount, seriesCount, journCount , diaryCount, cookCount, ArtCount, ComicCount, dictioCount, encycloCount, mathCount, religionCount, ScienceCount, healthCount, historyCount, sHelpCount, peotryCount } } }; Labels1 = new[] { "Science Fiction", "Drama", "Action/Adventure", "Romance", "Mystery", "Fantasy", "Biographies", "Trilogy", "Series", "Journals", "Diaries", "Cookbooks", "Art", "Comics", "Dictionaries", "Encyclopedias", "Math", "Religion", "Health", "History", "Self Help", "Poetry" }; Formatter1 = value => value.ToString("N"); }
public SpeedCharts() { if (WpfUtil.IsInDesignMode) { return; } this.Vm = new SpeedChartsViewModel(); this.DataContext = this.Vm; InitializeComponent(); if (WpfUtil.IsInDesignMode) { return; } Guid mainCoinId = NTMinerContext.Instance.MinerProfile.CoinId; this.OnLoaded((window) => { window.BuildEventPath <GpuSpeedChangedEvent>("显卡算力变更后刷新算力图界面", LogEnum.DevConsole, location: this.GetType(), PathPriority.Normal, path: (message) => { UIThread.Execute(() => { if (mainCoinId != NTMinerContext.Instance.MinerProfile.CoinId) { mainCoinId = NTMinerContext.Instance.MinerProfile.CoinId; foreach (var speedChartVm in Vm.SpeedChartVms.Items) { SeriesCollection series = speedChartVm.Series; SeriesCollection seriesShadow = speedChartVm.SeriesShadow; foreach (var item in series) { item.Values.Clear(); } foreach (var item in seriesShadow) { item.Values.Clear(); } } } IGpuSpeed gpuSpeed = message.Source; int index = gpuSpeed.Gpu.Index; if (Vm.SpeedChartVms.ContainsKey(index)) { SpeedChartViewModel speedChartVm = Vm.SpeedChartVms[index]; SeriesCollection series = speedChartVm.Series; SeriesCollection seriesShadow = speedChartVm.SeriesShadow; DateTime now = DateTime.Now; if (gpuSpeed.MainCoinSpeed != null && series.Count > 0) { IChartValues chartValues = series[0].Values; chartValues.Add(new MeasureModel() { DateTime = gpuSpeed.MainCoinSpeed.SpeedOn, Value = gpuSpeed.MainCoinSpeed.Value }); if (((MeasureModel)chartValues[0]).DateTime.AddMinutes(NTMinerContext.SpeedHistoryLengthByMinute) < now) { chartValues.RemoveAt(0); } chartValues = seriesShadow[0].Values; chartValues.Add(new MeasureModel() { DateTime = gpuSpeed.MainCoinSpeed.SpeedOn, Value = gpuSpeed.MainCoinSpeed.Value }); if (((MeasureModel)chartValues[0]).DateTime.AddMinutes(NTMinerContext.SpeedHistoryLengthByMinute) < now) { chartValues.RemoveAt(0); } } if (gpuSpeed.DualCoinSpeed != null && series.Count > 1) { IChartValues chartValues = series[1].Values; chartValues.Add(new MeasureModel() { DateTime = gpuSpeed.DualCoinSpeed.SpeedOn, Value = gpuSpeed.DualCoinSpeed.Value }); if (((MeasureModel)chartValues[0]).DateTime.AddMinutes(NTMinerContext.SpeedHistoryLengthByMinute) < now) { chartValues.RemoveAt(0); } chartValues = seriesShadow[1].Values; chartValues.Add(new MeasureModel() { DateTime = gpuSpeed.DualCoinSpeed.SpeedOn, Value = gpuSpeed.DualCoinSpeed.Value }); if (((MeasureModel)chartValues[0]).DateTime.AddMinutes(NTMinerContext.SpeedHistoryLengthByMinute) < now) { chartValues.RemoveAt(0); } } speedChartVm.SetAxisLimits(now); } }); }); }); Vm.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) => { if (e.PropertyName == nameof(Vm.CurrentSpeedChartVm)) { SpeedChartViewModel currentItem = Vm.CurrentSpeedChartVm; if (currentItem != null) { foreach (var item in _chartDic.Values) { item.Visibility = Visibility.Collapsed; } CartesianChart chart; if (!_chartDic.ContainsKey(currentItem)) { chart = new CartesianChart() { DisableAnimations = true, Hoverable = false, DataTooltip = null, Background = WpfUtil.WhiteBrush, Padding = new Thickness(4, 0, 0, 0), Visibility = Visibility.Visible }; chart.Series = currentItem.SeriesShadow; chart.AxisX = currentItem.AxisXShadow; chart.AxisY = currentItem.AxisYShadow; _chartDic.Add(currentItem, chart); DetailsGrid.Children.Add(chart); } else { chart = _chartDic[currentItem]; chart.Visibility = Visibility.Visible; } } } }; Vm.CurrentSpeedChartVm = Vm.SpeedChartVms.Items.FirstOrDefault(); if (AppRoot.MinerProfileVm.CoinVm != null) { Guid coinId = AppRoot.MinerProfileVm.CoinId; foreach (var item in NTMinerContext.Instance.GpuSet.AsEnumerable()) { List <IGpuSpeed> gpuSpeedHistory = item.GetGpuSpeedHistory(); SpeedChartViewModel speedChartVm = Vm.SpeedChartVms[item.Index]; SeriesCollection series = speedChartVm.Series; SeriesCollection seriesShadow = speedChartVm.SeriesShadow; DateTime now = DateTime.Now; foreach (var gpuSpeed in gpuSpeedHistory) { if (gpuSpeed.MainCoinSpeed != null && series.Count > 0) { series[0].Values.Add(new MeasureModel() { DateTime = gpuSpeed.MainCoinSpeed.SpeedOn, Value = gpuSpeed.MainCoinSpeed.Value }); seriesShadow[0].Values.Add(new MeasureModel() { DateTime = gpuSpeed.MainCoinSpeed.SpeedOn, Value = gpuSpeed.MainCoinSpeed.Value }); } if (gpuSpeed.DualCoinSpeed != null && series.Count > 1) { series[0].Values.Add(new MeasureModel() { DateTime = gpuSpeed.DualCoinSpeed.SpeedOn, Value = gpuSpeed.DualCoinSpeed.Value }); seriesShadow[0].Values.Add(new MeasureModel() { DateTime = gpuSpeed.DualCoinSpeed.SpeedOn, Value = gpuSpeed.DualCoinSpeed.Value }); } } IChartValues values = series[0].Values; if (values.Count > 0 && ((MeasureModel)values[0]).DateTime.AddMinutes(NTMinerContext.SpeedHistoryLengthByMinute) < now) { series[0].Values.RemoveAt(0); } values = seriesShadow[0].Values; if (values.Count > 0 && ((MeasureModel)values[0]).DateTime.AddMinutes(NTMinerContext.SpeedHistoryLengthByMinute) < now) { seriesShadow[0].Values.RemoveAt(0); } speedChartVm.SetAxisLimits(now); } } }
//audience chart init public void RaudienceBookItnit() { string query = "SELECT COUNT (*) FROM RBooks WHERE [Audience] = 'Kid'"; SqlCeCommand cmd = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int kidCount = (int)cmd.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM RBooks WHERE [Audience] = 'Teenager'"; SqlCeCommand cmd2 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int teenCount = (int)cmd2.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM RBooks WHERE [Audience] = 'Young Adult'"; SqlCeCommand cmd3 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int yAdCount = (int)cmd3.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM RBooks WHERE [Audience] = 'Adult'"; SqlCeCommand cmd4 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int adultCount = (int)cmd4.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM RBooks WHERE [Audience] = 'Mid aged'"; SqlCeCommand cmd5 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int mAgeCount = (int)cmd5.ExecuteScalar(); databaseConnection.Close(); query = "SELECT COUNT (*) FROM RBooks WHERE [Audience] = 'Elderly'"; SqlCeCommand cmd6 = new SqlCeCommand(query, databaseConnection); databaseConnection.Open(); int oldCount = (int)cmd6.ExecuteScalar(); databaseConnection.Close(); SeriesCollection4 = new SeriesCollection { new ColumnSeries { Title = "Number", Values = new ChartValues <double> { kidCount, teenCount, yAdCount, adultCount, mAgeCount, oldCount } } }; Labels4 = new[] { "Kid", "Teenager", "Young Adult", "adult", "Mid Aged", "Elderly" }; Formatter4 = value => value.ToString("N"); }
public void UserControl_Initialized(object sender, EventArgs e) { //top sell var bestSellProduct = (db.Products.GroupJoin(db.PurchaseDetails, p => p.Product_ID, d => d.Product_ID, (p, group) => new { Name = p.Product_Name, Thumbnail = p.Photos.FirstOrDefault().Data, Count = "Đã bán " + group.Count() + " sản phẩm" })).OrderByDescending(x => x.Count).ToList().Take(10); bestSellProductListView.ItemsSource = bestSellProduct; //sap het hang var almostOverProduct = (from product in db.Products where product.Quantity < 10 select new { Id = product.Product_ID, Name = product.Product_Name, Price = product.Price, Quantity = "Còn " + product.Quantity + " sản phẩm", Thumbnail = product.Photos.FirstOrDefault().Data }).ToList(); almostOverProductListView.ItemsSource = almostOverProduct; // Chart purchaseData = new SeriesCollection() { }; category_productData = new SeriesCollection() { }; var purchase = (db.Purchases.GroupJoin(db.PurchaseStatusEnums, p => p.Status, s => s.Value, (p, group) => new { Name = p.PurchaseStatusEnum.Display_Text, })).ToList(); foreach (var item in purchase.GroupBy(x => x.Name).Select(g => new { g.Key, Count = g.Count() })) { PieSeries Pie = new PieSeries() { Values = new ChartValues <float> { item.Count }, Title = $"{item.Key}" }; purchaseData.Add(Pie); } var category_product = (db.Products.GroupJoin(db.Categories, p => p.Catgory_ID, c => c.Category_ID, (p, group) => new { Name = p.Category.Category_Name, })).ToList(); foreach (var item in category_product.GroupBy(x => x.Name).Select(g => new { g.Key, Count = g.Count() })) { PieSeries Pie = new PieSeries() { Values = new ChartValues <float> { item.Count }, Title = $"{item.Key}" }; category_productData.Add(Pie); } category_product_piechart.Series = category_productData; purchase_pie_chart.Series = purchaseData; }
private void ConstructPlot2() { if (DataSource != null) { var BHPChartValues = new ChartValues <ScatterPoint>(); var dPdGChartValues = new ChartValues <ScatterPoint>(); var GdPdGChartValues = new ChartValues <ScatterPoint>(); var SelectedData = DataSource.Where((x) => x.Time >= EndPumping && x.Time <= EndDecline); foreach (var log in SelectedData) { var InitialTime = SelectedData.ElementAt(0).Time; var DeltaT = (log.Time - InitialTime) / InitialTime; var gDtD = (1 + DeltaT) * (Math.Asin(Math.Pow((1 + DeltaT), -0.5)) + Math.Pow(DeltaT, 0.5)); var xValue = 4 / Math.PI * (gDtD - Math.PI / 2); var BHPPoint = new ScatterPoint(); BHPPoint.X = xValue; BHPPoint.Y = log.SurfacePressure + Phydrostatic; BHPPoint.Weight = 1; BHPChartValues.Add(BHPPoint); } for (int i = 0; i < BHPChartValues.Count - 2; i++) { var tempDPDG = (BHPChartValues.ElementAt(i).Y - BHPChartValues.ElementAt(i + 2).Y) / (BHPChartValues.ElementAt(i + 2).X - BHPChartValues.ElementAt(i).X); var dPdGPoint = new ScatterPoint(); dPdGPoint.X = BHPChartValues.ElementAt(i).X; dPdGPoint.Y = tempDPDG; dPdGPoint.Weight = 1; dPdGChartValues.Add(dPdGPoint); } for (int i = 0; i < dPdGChartValues.Count; i++) { var tempGDPDG = dPdGChartValues.ElementAt(i).Y *dPdGChartValues.ElementAt(i).X; var GdPdGPoint = new ScatterPoint(); GdPdGPoint.X = dPdGChartValues.ElementAt(i).X; GdPdGPoint.Y = tempGDPDG; GdPdGPoint.Weight = 1; GdPdGChartValues.Add(GdPdGPoint); } PlotTwoSeries = new SeriesCollection { new ScatterSeries { Values = BHPChartValues, MinPointShapeDiameter = 5, MaxPointShapeDiameter = 5, Title = "BHP", ScalesYAt = 0, Fill = Brushes.Red }, new ScatterSeries { Values = dPdGChartValues, MinPointShapeDiameter = 5, MaxPointShapeDiameter = 5, Title = "dP/dG", ScalesYAt = 1, Fill = Brushes.Blue }, new ScatterSeries { Values = GdPdGChartValues, MinPointShapeDiameter = 5, MaxPointShapeDiameter = 5, Title = "GdP/dG", ScalesYAt = 1, Fill = Brushes.Green } }; } }
public static void DrawPoziomOdpaduChart() { if (DataContainer.guiState == null) { return; } LiveCharts.WinForms.CartesianChart poziomOdpaduChart = DataContainer.poziomOdpaduChart; poziomOdpaduChart.Series.Clear(); poziomOdpaduChart.AxisX.Clear(); poziomOdpaduChart.AxisY.Clear(); var finishedOrders = DataContainer.sqlDataByOrder.Where(order => order.Value.kitting.endDate >= DataContainer.guiState.viTabs.poziomOdpaduTab.startDate && order.Value.kitting.endDate <= DataContainer.guiState.viTabs.poziomOdpaduTab.endDate); if (!DataContainer.guiState.viTabs.poziomOdpaduTab.lgOrders) { finishedOrders = finishedOrders.Where(order => order.Value.kitting.odredGroup != "LG"); } if (!DataContainer.guiState.viTabs.poziomOdpaduTab.mstOrders) { finishedOrders = finishedOrders.Where(order => order.Value.kitting.odredGroup != "MST"); } var sortedOrders = finishedOrders.OrderBy(o => o.Value.kitting.endDate); string lineKey = DataContainer.guiState.viTabs.poziomOdpaduTab.cumulatedLines ? "Skumulowany" : "Po linii"; string[] selectedLines = DataContainer.guiState.viTabs.poziomOdpaduTab.selectedLines; Dictionary <string, Dictionary <string, WastePerPointStruct> > chartPoints = new Dictionary <string, Dictionary <string, WastePerPointStruct> >(); foreach (var smtLine in selectedLines) { chartPoints.Add(smtLine, new Dictionary <string, WastePerPointStruct>()); } foreach (var orderEntry in sortedOrders) { if (orderEntry.Value.smt.totalManufacturedQty == 0) { continue; } if (lineKey != "Skumulowany") { lineKey = orderEntry.Value.smt.smtOrders[0].smtLine; if (!selectedLines.Contains(lineKey)) { continue; } } string dateKey = GetDateKey(DataContainer.guiState.viTabs.poziomOdpaduTab.timeInterval, orderEntry.Value.kitting.endDate); foreach (var lineEntry in chartPoints) { if (!chartPoints[lineEntry.Key].ContainsKey(dateKey)) { chartPoints[lineEntry.Key].Add(dateKey, new WastePerPointStruct()); } } chartPoints[lineKey][dateKey].totalProduction += orderEntry.Value.smt.totalManufacturedQty; chartPoints[lineKey][dateKey].totalNg += orderEntry.Value.visualInspection.ngCount; chartPoints[lineKey][dateKey].totalScrap += orderEntry.Value.visualInspection.scrapCount; } SeriesCollection seriesCollection = new SeriesCollection(); ChartValues <float> totalProdValues = new ChartValues <float>(); List <string> labels = new List <string>(); foreach (var dateEntry in chartPoints[chartPoints.Select(k => k.Key).First()]) { labels.Add(dateEntry.Key); totalProdValues.Add(0); } foreach (var lineEntry in chartPoints) { int day = 0; foreach (var dateKey in labels) { totalProdValues[day] += lineEntry.Value[dateKey].totalProduction; day++; } } ColumnSeries totalProductionSeries = new ColumnSeries(); totalProductionSeries.Fill = new SolidColorBrush { Color = System.Windows.Media.Color.FromArgb(255, 50, 50, 50), Opacity = .4 }; totalProductionSeries.ScalesYAt = 0; totalProductionSeries.Values = totalProdValues; totalProductionSeries.Title = "Produkcja"; Axis axX = new Axis(); axX.Labels = labels; Axis axY1 = new Axis(); axY1.Position = AxisPosition.RightTop; axY1.Separator.IsEnabled = false; Axis axY2 = new Axis(); poziomOdpaduChart.AxisX.Add(axX); poziomOdpaduChart.AxisY.Add(axY1); poziomOdpaduChart.AxisY.Add(axY2); seriesCollection.Add(totalProductionSeries); foreach (var lineEntry in chartPoints) { ChartValues <float> ngValues = new ChartValues <float>(); ChartValues <float> scrapValues = new ChartValues <float>(); foreach (var dateEntry in lineEntry.Value) { if (dateEntry.Value.totalProduction > 0) { ngValues.Add((float)Math.Round((float)dateEntry.Value.totalNg / (float)dateEntry.Value.totalProduction * 100, 2)); scrapValues.Add((float)Math.Round((float)dateEntry.Value.totalScrap / (float)dateEntry.Value.totalProduction * 100, 2)); } else { ngValues.Add(0); scrapValues.Add(0); } } LineSeries ngSeries = new LineSeries(); ngSeries.Title = $"ng_{lineEntry.Key}"; ngSeries.Values = ngValues; ngSeries.DataLabels = true; ngSeries.ScalesYAt = 1; Func <ChartPoint, string> ngPt = pt => Math.Round(pt.Y, 2).ToString() + "%"; ngSeries.LabelPoint = ngPt; ngSeries.Stroke = MediaTools.ColorDrawingToMediaBrush(GlobalParameters.smtLinesColors[lineEntry.Key.ToUpper()]); ngSeries.Fill = new SolidColorBrush { Color = MediaTools.ColorDrawingToColorMedia(GlobalParameters.smtLinesColors[lineEntry.Key.ToUpper()]), Opacity = 0.4 }; ngSeries.PointGeometry = DefaultGeometries.Square; LineSeries scrapSeries = new LineSeries(); scrapSeries.Values = scrapValues; scrapSeries.Title = $"scrap_{lineEntry.Key}"; scrapSeries.LabelPoint = ngPt; scrapSeries.DataLabels = true; scrapSeries.ScalesYAt = 1; scrapSeries.Fill = new SolidColorBrush { Color = (MediaTools.ColorDrawingToColorMedia(GlobalParameters.smtLinesColors[lineEntry.Key.ToUpper()])), Opacity = 0.4 }; scrapSeries.Stroke = MediaTools.ColorDrawingToMediaBrush(GlobalParameters.smtLinesColors[lineEntry.Key.ToUpper()]); seriesCollection.Add(ngSeries); seriesCollection.Add(scrapSeries); //poziomOdpaduChart.Series.Add(ngSeries); //poziomOdpaduChart.Series.Add(scrapSeries); } poziomOdpaduChart.Series.AddRange(seriesCollection); poziomOdpaduChart.Zoom = ZoomingOptions.Xy; poziomOdpaduChart.Pan = PanningOptions.Xy; }
public MainWindow() { InitializeComponent(); SeriesCollection = new SeriesCollection { new ColumnSeries { Title = "2015", Values = new ChartValues <double> { 10, 50, 39, 50 } } }; //adding series will update and animate the chart automatically SeriesCollection.Add(new ColumnSeries { Title = "2016", Values = new ChartValues <double> { 11, 56, 42 } }); //also adding values updates and animates the chart automatically SeriesCollection[1].Values.Add(48d); Labels = new[] { "Maria", "Susan", "Charles", "Frida" }; Formatter = value => value.ToString("N"); DataContext = this; SeriesCollection1 = new SeriesCollection { new LineSeries { Title = "Series 1", Values = new ChartValues <double> { 4.3, 6, 5.7, 2, 4.1 } } }; Labels1 = new[] { "Jan", "Feb", "Mar", "Apr", "May" }; YFormatter = value => value.ToString("C"); DataContext = this; PointLabel = chartPoint => string.Format("{0} ({1:P})", chartPoint.Y, chartPoint.Participation); DataContext = this; SeriesCollection2 = new SeriesCollection { new ScatterSeries { Values = new ChartValues <ScatterPoint> { new ScatterPoint(5, 5, 20), new ScatterPoint(3, 4, 80), new ScatterPoint(7, 2, 20), new ScatterPoint(2, 6, 60), new ScatterPoint(8, 2, 70) }, MinPointShapeDiameter = 15, MaxPointShapeDiameter = 45 }, new ScatterSeries { Values = new ChartValues <ScatterPoint> { new ScatterPoint(7, 5, 1), new ScatterPoint(2, 2, 1), new ScatterPoint(1, 1, 1), new ScatterPoint(6, 3, 1), new ScatterPoint(8, 8, 1) }, PointGeometry = DefaultGeometries.Triangle, MinPointShapeDiameter = 15, MaxPointShapeDiameter = 45 } }; DataContext = this; }
public PointPropertyChangedBar() { InitializeComponent(); //create a config for StoreViewModel var config = new SeriesConfiguration<StoreViewModel>() .Y(y => y.Income); //use Income property as Y //do not configure X //this will pull a zero based index as X //create a SeriesCollection with this config StoresCollection = new SeriesCollection(config); //add some Series with ChartValues<StoreViewModel> StoresCollection.Add(new BarSeries { Title = "Apple Store", Values = new ChartValues<StoreViewModel> { new StoreViewModel {Income = 15} } }); StoresCollection.Add(new BarSeries { Title = "Google Play", Values = new ChartValues<StoreViewModel> { new StoreViewModel {Income = 5} } }); DataContext = this; }