How To Reduce Column Series Gap In DotNet.Highcharts - c#

I am creating my chart using DotNet.Highchart Library, i have a problem in reducing gap between data series in column chart. This is my current Chart :
and this is my current column chart code:
DotNet.Highcharts.Highcharts AttritionByReasonBarChart = new DotNet.Highcharts.Highcharts("AttritionByReasonBarChart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column, Height = 400, Width = 860, Style = "margin: '0 auto'" })
.SetTitle(new Title { Text = "Attrition by Reason", Style = "font: 'normal 16px Verdana, sans-serif'" })
.SetCredits(new Credits { Enabled = false })
.SetXAxis(new XAxis
{
Categories = vEmployment,
Labels = new XAxisLabels { Rotation = 0 }
})
.SetYAxis(new YAxis
{
Title = new YAxisTitle
{
Text = "Employment Type",
Align = AxisTitleAligns.Middle
}
})
.SetPlotOptions(new PlotOptions
{
Bar = new PlotOptionsBar
{
DataLabels = new PlotOptionsBarDataLabels { Enabled = true }
}
})
.SetLegend(new Legend
{
Layout = Layouts.Vertical,
Align = HorizontalAligns.Right,
VerticalAlign = VerticalAligns.Middle,
Floating = true,
BorderWidth = 1,
BackgroundColor = new BackColorOrGradient(ColorTranslator.FromHtml("#FFFFFF")),
Shadow = true
})
.SetSeries(
new Series
{
Name = "Head Count",
Data = new Data(vTotal)
});
Is there any best way to set the gap between data series?
Thanks

Replace PlotOptionsBar with PlotOptionsColumn and add PointPadding to your code as below:
Highcharts AttritionByReasonBarChart = new Highcharts("AttritionByReasonBarChart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column, Height = 400, Width = 860, Style = "margin: '0 auto'" })
.SetTitle(new Title { Text = "Attrition by Reason", Style = "font: 'normal 16px Verdana, sans-serif'" })
.SetCredits(new Credits { Enabled = false })
.SetXAxis(new XAxis
{
Categories = new[] { "ABHFGFGETTRRD AGAGGSGSGS", "IEKHLTOTUYYT IIWWIIWEUEUEU", "KMVMVBBV DGDFEFJ", "KRJG JGJGJGT", "HAHAHSHSGD OTERETETE ET", "HAHAHA PRGDGDGDGDG DGT", "NRIRITITITITI WP", "DFC AHAHSSGGDF" },
Labels = new XAxisLabels { Rotation = 0 }
})
.SetYAxis(new YAxis
{
Title = new YAxisTitle
{
Text = "Employment Type",
Align = AxisTitleAligns.Middle
}
})
.SetPlotOptions(new PlotOptions
{
Column = new PlotOptionsColumn
{
PointPadding = -0.2,
DataLabels = new PlotOptionsColumnDataLabels { Enabled = false }
}
})
.SetLegend(new Legend
{
Layout = Layouts.Vertical,
Align = HorizontalAligns.Right,
VerticalAlign = VerticalAligns.Middle,
Floating = true,
BorderWidth = 1,
BackgroundColor = new BackColorOrGradient(ColorTranslator.FromHtml("#FFFFFF")),
Shadow = true
})
.SetSeries(
new Series
{
Name = "Head Count",
Data = new Data(new object[] { 30,10,5,20,5,10,25,15 })
});

Related

WPF Bar Chart how to add space between bars?

I am using Telerik (RadPieChart) with WPF. What I want to do is add a small space between the bars. I am not asking about the space between the series, as that is already available, but about a smaller space between the bars just as shown in the image examples below.
Here is what I have now:
And this is how I would like my Bar Chart to look like with a small space between them:
This is my source code:
private BarSeries CreateBarSeries(KeyValuePair<ChartSerie, List<ChartDataPoint>> chartSeries, ChartLegendSettings legendSettings, int colorPaletteIndex)
{
var isStackMode = chartSeries.Key.CombineMode == SeriesCombineMode.Stack;
var barSerie = new BarSeries()
{
VerticalAxis = CreateMultipleVerticalAxis(chartSeries, colorPaletteIndex, out var multipleVerticalAxis) ? multipleVerticalAxis : null,
LegendSettings = legendSettings,
StackGroupKey = chartSeries.Key.Group,
Opacity = 0.8,
ZIndex = 120,
CombineMode = string.IsNullOrEmpty(chartSeries.Key.Group)
? ChartSeriesCombineMode.Cluster
: (isStackMode ? ChartSeriesCombineMode.Stack : ChartSeriesCombineMode.Stack100),
// start animations
//PointAnimation = new ChartMoveAnimation()
//{
// MoveAnimationType = MoveAnimationType.Bottom,
// Duration = new TimeSpan(0, 0, 0, 0, 600),
// Delay = new TimeSpan(0, 0, 0, 0, 155),
// //Easing = new ElasticEase()
// //{
// // EasingMode = EasingMode.EaseOut,
// //},
//},
LabelDefinitions =
{
// set the clarion format for the labels
new ChartSeriesLabelDefinition()
{
Template = new DataTemplate()
{
VisualTree = GetSeriesFormat(chartSeries),
}
}
}
};
// this is the color of bar series
if (chartSeries.Key.ColorHex != null)
{
Style style = new Style(typeof(Border));
style.Setters.Add(new Setter(Border.BackgroundProperty, (SolidColorBrush)(new BrushConverter().ConvertFrom(chartSeries.Key.ColorHex))));
barSerie.DefaultVisualStyle = style;
}
foreach (ChartDataPoint serie in chartSeries.Value)
{
barSerie.DataPoints.Add(new CategoricalDataPoint()
{
Category = serie.XPoint.Label,
Value = (double?)serie.Value,
});
}
return barSerie;
}
The answer:
For some reason adding the BorderThickness to the Style as suggested in one of the answers did not do the trick, although BorderThicknes should be the solution. So I added a PointTemplate with a VisualTree and there I defined the BorderThickness. Now it is working perfectly.
private BarSeries CreateBarSeries(KeyValuePair<ChartSerie, List<ChartDataPoint>> chartSeries, ChartLegendSettings legendSettings, int colorPaletteIndex)
{
var seriesPredefinedColor = this.ChartBase.Palette.GlobalEntries[colorPaletteIndex].Fill;
FrameworkElementFactory borderFramework = new FrameworkElementFactory(typeof(Border));
borderFramework.SetValue(Border.BackgroundProperty, ColorService.BrushFromHex(chartSeries.Key.ColorHex) ?? seriesPredefinedColor);
borderFramework.SetValue(Border.OpacityProperty, 0.8D);
borderFramework.SetValue(Border.BorderThicknessProperty, new Thickness(2));
borderFramework.AddHandler(Border.MouseEnterEvent, new MouseEventHandler((sender, args) =>
{
var seriesBorder = (Border)sender;
//seriesBorder.BorderBrush = new SolidColorBrush(Colors.Black);
//seriesBorder.BorderThickness = new Thickness(1);
seriesBorder.Opacity = 1;
}));
borderFramework.AddHandler(Border.MouseLeaveEvent, new MouseEventHandler((sender, args) =>
{
var seriesBorder = (Border)sender;
//seriesBorder.BorderBrush = new SolidColorBrush(Colors.Black);
//seriesBorder.BorderThickness= new Thickness(1);
seriesBorder.Opacity = 0.8;
}));
var isStackMode = chartSeries.Key.CombineMode == SeriesCombineMode.Stack;
var barSerie = new BarSeries()
{
VerticalAxis = CreateMultipleVerticalAxis(chartSeries, colorPaletteIndex, out var multipleVerticalAxis) ? multipleVerticalAxis : null,
LegendSettings = legendSettings,
StackGroupKey = chartSeries.Key.Group,
ZIndex = 120,
IsHitTestVisible = true,
CombineMode = string.IsNullOrEmpty(chartSeries.Key.Group)
? ChartSeriesCombineMode.Cluster
: (isStackMode ? ChartSeriesCombineMode.Stack : ChartSeriesCombineMode.Stack100),
// start animations
//PointAnimation = new ChartMoveAnimation()
//{
// MoveAnimationType = MoveAnimationType.Bottom,
// Duration = new TimeSpan(0, 0, 0, 0, 600),
// Delay = new TimeSpan(0, 0, 0, 0, 155),
// //Easing = new ElasticEase()
// //{
// // EasingMode = EasingMode.EaseOut,
// //},
//},
LabelDefinitions =
{
// set the clarion format for the labels
new ChartSeriesLabelDefinition()
{
Template = new DataTemplate()
{
VisualTree = GetSeriesFormat(chartSeries),
}
}
},
PointTemplate = new DataTemplate()
{
VisualTree = borderFramework,
}
};
// this is the color of bar series
//if (chartSeries.Key.ColorHex != null)
//{
// Style style = new Style(typeof(Border));
// style.Setters.Add(new Setter(Border.BackgroundProperty, (SolidColorBrush)(new BrushConverter().ConvertFrom(chartSeries.Key.ColorHex))));
// barSerie.DefaultVisualStyle = style;
//}
foreach (ChartDataPoint serie in chartSeries.Value)
{
barSerie.DataPoints.Add(new CategoricalDataPoint()
{
Category = serie.XPoint.Label,
Value = (double?)serie.Value,
});
}
return barSerie;
}
Set the BorderThickness property of the DefaultVisualStyle of the BarSeries:
// this is the color of bar series
if (chartSeries.Key.ColorHex != null)
{
Style style = new Style(typeof(Border));
style.Setters.Add(new Setter(Border.BackgroundProperty, (SolidColorBrush)(new BrushConverter().ConvertFrom(chartSeries.Key.ColorHex))));
style.Setters.Add(new Setter(Border.BorderThicknessProperty, new Thickness(2.0)));
barSerie.DefaultVisualStyle = style;
}
have you look into this ? seem default is 0 mean bar take all the space
Scale.SpacingSlotCount Property
Determines the number of space slots that will be left around the DataPoints per category slot, measured relatively to the DataPoint
slot's width: Empty Space = SpacingSlotCount * DataPoint_SlotWidth
Namespace: Telerik.Reporting
Assembly: Telerik.Reporting (in Telerik.Reporting.dll) Version: 12.1.18.816 (12.1.18.816)

Xamarin bind a dynamic list of images to a grid

first of all sorry for the mess, I'm kicking my head in this for a while already, I'm kind new in xamarin and starting with difficult problems. I'm trying to add dynamically a list of random images in a grid.
currently i have the grid printing like
Name1 Detail1
filename1 filename2 filename3
Name2 Detail2
Filename1 filename2
var cell = new DataTemplate(() => {
var grid = new Grid() { Padding = 8, RowSpacing = 5, ColumnSpacing = 5 };
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(50, GridUnitType.Star) });
Subtitle.SetBinding(Label.TextProperty, "Images");
grid.Children.Add(labelName, 0, 0);
grid.Children.Add(labelDetail, 1, 0);
grid.Children.Add(Subtitle, 1, 1);
the cell in the end is attached to a listview
listdata.ItemTemplate = cell;
in the Object I have defined images as a string, I already tried to create another bind to a list, and create a listview of a custom call and add it to the grid, but throws an error and I can't see any description, it's something like sigsegv-without-stack trace
Also tried to instead of a grid, create a stack layout. again nothing.
CustomCell
public class CustomNocCell : ViewCell
{
public CustomCell()
{
//instantiate each of our views
var image = new Image();
var nameLabel = new Label();
var typeLabel = new Label();
var verticaLayout = new StackLayout();
var horizontalLayout = new StackLayout() { BackgroundColor = Color.Transparent };
//set bindings
nameLabel.SetBinding(Label.TextProperty, new Binding("Name"));
image.SetBinding(Image.SourceProperty, new Binding("Image"));
//Set properties for desired design
horizontalLayout.Orientation = StackOrientation.Horizontal;
horizontalLayout.HorizontalOptions = LayoutOptions.Center;
image.HorizontalOptions = LayoutOptions.End;
nameLabel.FontSize = 24;
//add views to the view hierarchy
verticaLayout.Children.Add(nameLabel);
horizontalLayout.Children.Add(verticaLayout);
horizontalLayout.Children.Add(image);
// add to parent view
View = horizontalLayout;
}
}
what I tried already that gave the error
//ListView listView = new ListView();
//listView.RowHeight = 60;
//listView.ItemTemplate = new DataTemplate(typeof(CustomNocCell));
////listView.ItemsSource = "ImagesNoc";
//listView.SetBinding(ListView.ItemsSourceProperty, "ImagesList");
ImagesList class
[Ignore]
public ListView ImagesList
{
get
{
ListView listView = new ListView();
listView.RowHeight = 60;
listView.ItemTemplate = new DataTemplate(typeof(CustomNocCell));
List<string> list = new List<string>();
if (!string.IsNullOrEmpty(Detail))
{
foreach (string str in Detail.Split(';'))
{
list.Add(str);
}
}
listView.ItemsSource = list.Select(s => new { Name = s, Image = s.ToLower() + ".png" }).ToList();
return listView;
}
}
I had the class also returning a simple List of type Name and Image that the CustomCell is waiting and nothing.
EDIT
public class TestObject
{
public string title { get; set; }
public string countries { get; set; }
}
void load()
{
List<TestObject> list = new List<TestObject>();
list.Add(new TestObject { title = "test1", countries = "esp,ita,prt" });
list.Add(new TestObject { title = "test2", countries = "esp,ita" });
list.Add(new TestObject { title = "test3", countries = "rus" });
var labelTitle = new Label()
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
VerticalOptions = LayoutOptions.StartAndExpand,
};
listdata = new ListView();
listdata.ItemsSource = list;
var cell = new DataTemplate(() => {
var grid = new Grid() { Padding = 8, RowSpacing = 5, ColumnSpacing = 5 };
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
labelTitle.SetBinding(Label.TextProperty, "title");
countriesLabel.SetBinding(Label.TextProperty, "countries"); //here i want to make a customcell to show the images, like be able to "bind" and calc the countries split the string by "," and add (name + ".png") then show the image.
// i was able to do it in a listview when i have the source in my side.. in this one i have to bind and then calc..
grid.Children.Add(labelTitle, 0, 0);
grid.Children.Add(countriesLabel, 1, 0);
});
listdata.ItemTemplate = cell;
}

Unable to set desired background color in excel using openxml

I am new to open xml and trying to set the background color of header row to gray but it always set it to black. Please refer following code which I am using.
return new Stylesheet(
new Fonts(
new Font( // Index 0 - The default font.
new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 11 },
new Color() { Rgb = new HexBinaryValue() { Value = "000000" } },
new FontName() { Val = "Calibri" }),
new Font( // Index 1 - The bold white font.
new DocumentFormat.OpenXml.Spreadsheet.Bold(),
new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 11 },
new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = new HexBinaryValue() { Value = "ffffff" } },
new DocumentFormat.OpenXml.Spreadsheet.FontName() { Val = "Calibri" }),
new Font( // Index 2 - The bold red font.
new DocumentFormat.OpenXml.Spreadsheet.Bold(),
new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 11 },
new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = new HexBinaryValue() { Value = "ff0000" } },
new DocumentFormat.OpenXml.Spreadsheet.FontName() { Val = "Calibri" }),
new Font( // Index 2 - The bold red font.
new DocumentFormat.OpenXml.Spreadsheet.Bold(),
new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 11 },
new DocumentFormat.OpenXml.Spreadsheet.Color() { Rgb = new HexBinaryValue() { Value = "000000" } },
new DocumentFormat.OpenXml.Spreadsheet.FontName() { Val = "Calibri" })
),
new Fills(
new Fill( // Index 0 - The default fill.
new PatternFill() { PatternType = PatternValues.None }),
new Fill( // Index 1 - The default fill of gray 125 (required)
new PatternFill() { PatternType = PatternValues.Gray125 }),
new Fill( // Index 2 - The blue fill.
new PatternFill(
new ForegroundColor() { Rgb = new HexBinaryValue() { Value = "006699" } }
) { PatternType = PatternValues.Solid }),
new Fill( // Index 3 - The grey fill.
new PatternFill(
new BackgroundColor () { Rgb = new HexBinaryValue(){ Value = "808080" } }
)
{ PatternType = PatternValues.Solid }
)
),
new Borders(
new Border( // Index 0 - The default border.
new LeftBorder(),
new RightBorder(),
new TopBorder(),
new BottomBorder(),
new DiagonalBorder()),
new Border( // Index 1 - Applies a Left, Right, Top, Bottom border to a cell
new LeftBorder(
new Color() { Auto = true }
) { Style = BorderStyleValues.Thin },
new RightBorder(
new Color() { Auto = true }
) { Style = BorderStyleValues.Thin },
new TopBorder(
new Color() { Auto = true }
) { Style = BorderStyleValues.Thin },
new BottomBorder(
new Color() { Auto = true }
) { Style = BorderStyleValues.Thin },
new DiagonalBorder())
),
new CellFormats(
new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }) { FontId = 1, FillId = 0, BorderId = 0 }, // Index 0 - The default cell style. If a cell does not have a style index applied it will use this style combination instead
new CellFormat(
new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }
) { FontId = 1, FillId = 2, BorderId = 0, ApplyFont = true }, // Index 1 - Bold White Blue Fill
new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }
) { FontId = 2, FillId = 2, BorderId = 0, ApplyFont = true } , // Index 2 - Bold Red Blue Fill
new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }
)
{ FontId = 3, FillId = 3, BorderId = 0, ApplyFont = true }
)
); // return
Generated output:
Desired output:
Pls help me. Thanks in advance
The documentation for PatternFill (section 18.8.32 of the ECMA-376 standard) says (emphasis mine):
For solid cell fills (no
pattern), fgColor is used. For cell fills with patterns specified, then the cell fill color is specified by the bgColor
element.
You have specified PatternType = PatternValues.Solid but you are providing a BackgroundColor rather than a ForegroundColor. Changing from the BackgroundColor to the ForegroundColor will solve your issue i.e. this line:
new BackgroundColor() { Rgb = new HexBinaryValue(){ Value = "808080" } }
should become:
new ForegroundColor() { Rgb = new HexBinaryValue() { Value = "808080" } }

Xamarin forms RelativeLayout not appearing

I am following some pretty standard Xamarin forms tutorials and I am really struggling to get the RelativeLayout to work. Ultimately I want to have an ActivityIndicator overlaid on top of the mainContent:
BindingContext = new LoginViewModel(this);
Padding = new Thickness(20);
Title = "Login";
var image = new Image
{
Source = ImageSource.FromFile("logo.png"),
HeightRequest = 50
};
var label = new Label
{
Text = "...",
FontSize = 20,
HorizontalTextAlignment = TextAlignment.Center
};
var errorLabel = new Label
{
Text = "",
TextColor = Color.Red,
FontSize = 20,
HorizontalTextAlignment = TextAlignment.Center
};
var loginButton = new Button
{
Text = "Log In",
BackgroundColor = Color.Black,
TextColor = Color.White,
FontSize = 20,
HeightRequest = 50
};
var loginEntry = new Entry
{
Placeholder = "Username"
};
var passwordEntry = new Entry
{
Placeholder = "Password"
};
var copywrite = new Label
{
Text = "© 2016",
FontSize = 15,
HorizontalTextAlignment = TextAlignment.Center
};
var loadingIndicator = new ActivityIndicator
{
BackgroundColor = Color.Blue,
IsVisible = true
};
...
var topLayer = new StackLayout
{
Spacing = 10,
Children = { image, label, loginEntry, passwordEntry, loginButton, errorLabel },
VerticalOptions = LayoutOptions.Start
};
var bottomLayer = new StackLayout
{
Spacing = 10,
Children = { copywrite },
VerticalOptions = LayoutOptions.End
};
var mainContent = new StackLayout
{
Children =
{
topLayer,
new StackLayout
{
VerticalOptions = LayoutOptions.CenterAndExpand,
},
bottomLayer
},
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.Green
};
var r = new RelativeLayout()
{
BackgroundColor = Color.Pink
};
r.Children.Add(mainContent,
Constraint.RelativeToParent((parent) =>
{
return parent.Width;
}),
Constraint.RelativeToParent((parent) =>
{
return parent.Height;
})
);
Content = r;
When I set Content = mainContent I see everything fine, but with the above code I get a white screen. I have been looking here.
When I try this:
var overlay = new AbsoluteLayout()
{
BackgroundColor = Color.Pink
};
AbsoluteLayout.SetLayoutFlags(mainContent, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds(mainContent, new Rectangle(0f, 0f, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize));
AbsoluteLayout.SetLayoutFlags(loadingIndicator, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds(loadingIndicator, new Rectangle(0.5, 0.5, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize));
overlay.Children.Add(mainContent);
overlay.Children.Add(loadingIndicator);
Content = overlay;
I can see the Green and Pink views, but they may as well be stacked (as opposed to being overlaid) - but also I cannot see the Activity Indicator inside the Pink Absolute layout.
For the RelativeLayout, the Add method you are calling is setting a constraint on X and Y, not on width and height. The order of the parameters for that variant of Add is:
Child View
X constraint
Y constraint
Width constraint
Height constraint
With all constraints being optional.
To explicitly place it over the entire screen, do something like this:
r.Children.Add(mainContent,
Constraint.Constant(0),
Constraint.Constant(0),
Constraint.RelativeToParent((parent) =>
{
return parent.Width;
}),
Constraint.RelativeToParent((parent) =>
{
return parent.Height;
})
);
For the AbsoluteLayout, try a slightly different set of constraints:
AbsoluteLayout.SetLayoutFlags(mainContent, AbsoluteLayoutFlags.All);
AbsoluteLayout.SetLayoutBounds(mainContent, new Rectangle(0f, 0f, 1f, 1f));
This explicitly specifies that mainContent is to occupy the entire AbsoluteLayout rather than relying on the actual layout size of mainContent.

How to chart using Web.UI.DataVisualization.Charting?

using System.Web.UI.DataVisualization.Charting.Chart
I have data in 2 formats:
A.
B.
The data in format A is what I am using to build a chart. But my chart ends up looking like:
I cannot figure out how come no lines are drawn. Here is the code I am using:
var dataTable = GetDataTable();
var xAxisTitle = dataTable.Columns[1].ExtendedProperties["Type"].ToString();
var yAxisTitle = dataTable.Columns[0].ExtendedProperties["Type"].ToString();
chart = new Chart() {
AntiAliasing = AntiAliasingStyles.All,
TextAntiAliasingQuality = TextAntiAliasingQuality.High,
Width = 1200,
Height = 800,
Enabled = true,
ForeColor = Color.SaddleBrown
};
var chartArea = new ChartArea() {
BackColor = Color.White,
AxisY = new Axis() {
Enabled = AxisEnabled.True,
Title = yAxisTitle,
LineColor = Color.DarkBlue,
MajorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.DarkGreen,
Interval = .1d
},
MinorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.Green,
Interval = .1d
},
LabelStyle = new LabelStyle() {
Enabled = true,
ForeColor = Color.Red,
IsEndLabelVisible = true,
Font = new Font("Calibri", 4, FontStyle.Regular)
},
MajorGrid = new Grid() {
Enabled = true,
LineColor = Color.LightGray,
LineWidth = 1
},
},
AxisX = new Axis() {
Enabled = AxisEnabled.True,
Title = xAxisTitle,
LineColor = Color.DarkBlue,
MajorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.Red,
Interval = .1d
},
MinorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.DarkGreen,
Interval = .1d
},
LabelStyle = new LabelStyle() {
Enabled = true,
ForeColor = Color.Blue,
IsEndLabelVisible = true,
Font = new Font("Calibri", 4, FontStyle.Regular)
},
MajorGrid = new Grid() {
Enabled = true,
LineColor = Color.DarkGray,
LineWidth = 1
},
},
};
chartArea.AxisX.Enabled = AxisEnabled.True;
chartArea.AxisY.Enabled = AxisEnabled.True;
chart.ChartAreas.Add(chartArea);
var lineHeaders = dataTable.Rows
.OfType<DataRow>()
.Select(r => r[0].ToString())
.ToArray();
var i = 0;
for (int column = 0; column < lineHeaders.Length; column++) {
var header = lineHeaders[column];
var series = chart.Series[header] = new Series() {
Enabled = true,
Name = header,
Font = new Font("Lucida Sans Unicode", 6f),
Color = legendColors[header],
ChartType = SeriesChartType.Line,
XValueType = ChartValueType.DateTime,
YValueType = ChartValueType.Double,
};
var colData = dataTable.Rows[column]
.ItemArray
.Skip(1)
.Select(d => (double)d)
.ToArray();
DataPoint p = new DataPoint() {
AxisLabel = header,
XValue = i++,
YValues = colData,
};
series.Points.Add(p);
}
I've also set the data table as the data source on the Chart but there are no data points plotted.
Am I even using the correct data table ...should I be using format B instead?
I proceeded with the table format option B:
Other codes changes were minimal but re-posting the entire snippet below. The primary fix are these two lines at the end of the method:
chart.DataSource = DataTable;
chart.DataBind();
internal void BuildChart(DataTable DataTable) {
var xAxisTitle = DataTable.Columns[1].ExtendedProperties["Type"].ToString();
var yAxisTitle = DataTable.Columns[0].ExtendedProperties["Type"].ToString();
chart = new Chart() {
AntiAliasing = AntiAliasingStyles.All,
TextAntiAliasingQuality = TextAntiAliasingQuality.High,
Width = 1800,
Height = 500,
Enabled = true,
ForeColor = Color.SaddleBrown
};
#region build chart area
var chartArea = new ChartArea() {
BackColor = Color.White,
Name = DataTable.TableName,
AxisY = new Axis() {
Enabled = AxisEnabled.True,
Title = yAxisTitle,
LineColor = Color.DarkBlue,
MajorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.DarkGreen,
},
MinorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.Green,
},
LabelStyle = new LabelStyle() {
Enabled = true,
ForeColor = Color.Red,
IsEndLabelVisible = true,
Font = new Font("Calibri", 4, FontStyle.Regular)
},
MajorGrid = new Grid() {
Enabled = true,
LineColor = Color.LightGray,
LineWidth = 1
},
},
AxisX = new Axis() {
Enabled = AxisEnabled.True,
Title = xAxisTitle,
LineColor = Color.DarkBlue,
MajorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.Red,
},
MinorTickMark = new TickMark() {
Enabled = true,
LineColor = Color.DarkGreen,
},
LabelStyle = new LabelStyle() {
Enabled = true,
ForeColor = Color.Blue,
IsEndLabelVisible = true,
Font = new Font("Calibri", 4, FontStyle.Regular)
},
MajorGrid = new Grid() {
Enabled = true,
LineColor = Color.DarkGray,
LineWidth = 1
},
},
};
chartArea.AxisX.Enabled = AxisEnabled.True;
chartArea.AxisY.Enabled = AxisEnabled.True;
#endregion
chart.ChartAreas.Add(chartArea);
var seriesHeaders = DataTable.Columns
.OfType<DataColumn>()
.Skip(1)
.Select(c => c.ColumnName)
.ToArray();
chart.Legends.Add(new Legend(DataTable.TableName) {
Enabled = true
});
for (int column = 0; column < seriesHeaders.Length; column++) {
var header = seriesHeaders[column];
var series = chart.Series[header] = new Series(header) {
BorderWidth = 2,
ChartArea = DataTable.TableName,
ChartType = SeriesChartType.FastLine,
Color = legendColors[header],
Enabled = true,
Font = new Font("Lucida Sans Unicode", 6f),
XValueMember = "Week",
YValueMembers = header
};
series.EmptyPointStyle.MarkerColor = legendColors[header];
}
chart.DataSource = DataTable;
chart.DataBind();
}

Categories

Resources