Change bar chart axis scale using Aspose.Cells for C# - c#

I'm trying to set the axis scale for a bar chart using Aspose.Cells for C#. What I'm currently doing is essentially this:
var chart = worksheet.Charts.Add(ChartType.BarChart, 1, 1, 15, 15)
chart.NSeries.AddSeries("{.015,.03,.04}", true)
chart.NSeries.CategoryData = "{Apples,Oranges,Pears}"
chart.SeriesAxis.IsAutomaticMajorUnit = false;
chart.SeriesAxis.MajorUnit = .01;
However, when the spreadsheet renders the chart's major unit scale is automatically set to .1, so all the bars look disproportionately small. How can I change the scale of the series axis, so it has tick marks spaced apart by .01?

Please use the following code for your needs.
C#
//Set the major unit to 0.01
ch.ValueAxis.IsAutomaticMajorUnit = false;
ch.ValueAxis.MajorUnit = 0.01;
Here is the full sample code and the screenshot showing the output Excel file generated by the code for your reference.
C#
// Create empty workbook.
Workbook wb = new Workbook();
// Access first worksheet.
Worksheet worksheet = wb.Worksheets[0];
// Add Bar chart in first worksheet.
int idx = worksheet.Charts.Add(ChartType.Bar, 5, 2, 20, 10);
// Access Bar chart.
Chart ch = worksheet.Charts[0];
// Add two number series, true means they are vertical.
ch.NSeries.Add("{.015,.03,.04}", true);
// Set the category data to show on X-axis.
ch.NSeries.CategoryData = "{Apples,Oranges,Pears}";
// Set the name of first and second series.
ch.NSeries[0].Name = "Cricket";
//Set the major unit to 0.01
ch.ValueAxis.IsAutomaticMajorUnit = false;
ch.ValueAxis.MajorUnit = 0.01;
// Save the output in xlsx format.
wb.Save("outputBarChart.xlsx", SaveFormat.Xlsx);
Note: I am working as Developer Evangelist at Aspose

Related

Programmatic Creation of Chart and setting of its legends

I am creating Charts pie, bar and line and want to set their Legends along with valuea,Title of legend and point the values on Charts. how could i do so?
Usually you don't need to add a Legend as there is already a default one. But since you are creating a Chart in code you indeed have to code a little more. Adding a Legend is one of thoses things.
You have created a legend but instead of adding it you create another legend still. Instead write: chartA.Legends.Add(legend)
Note that the documentation (including Intellisense) is wrong on the constructor with a string paramenter! It works as expected, not as documented on MSDN!
What I suggested (chartA.Legends[0].Title = "someString";) works fine provided you have done all the other things you need:
You will also have to create (at least)
One ChartArea
One Series along with the ChartTypeyou want an..
..in order to make it show you also have to add a DataPoint.
Example:
Legend legend = new Legend();
Chart chartA = new Chart(); // <<---!
chartA.BackColor = Color.White;
chartA.Width = 370;
chartA.Height = 250;
chartA.Location = new Point(48, 35);
chartA.Name = textBox1.Text;
chartA.Legends.Add(legend); // <<---!
legend.Title = "Age of The Employees"; // <<---!
chartA.ChartAreas.Add(new ChartArea("ca")); // <<---!
chartA.ChartAreas["ca"].BackColor = Color.LightSeaGreen;
Series s1 = chartA.Series.Add("s1"); // <<---!
s1.ChartType = SeriesChartType.Pie;
s1.Points.AddY(12);
s1.Points.AddY(32);
..
The first Legend will automatically be filled with either one LegendItem per Series or (if you have a Pie chart) one item per DataPoint
Btw: You may have additional Legends but you will have to take care of their content and their position/docking..
Update: If you want to you can take control of both the Legend's Font and the TitleFont; It works the usual way, i.e. by creating a new Font, either from scratch of from the FontFamily of a Font:
legend.Font = new Font("Consolas", 10f);
legend.TitleFont = new Font(legend.Font.FontFamily, 14f);
You may want to insert a newline character (\n) into the title if it is too long to fit into a vertical Legend..

Programatically show tooltip in Live Charts

I have an application that have 2 charts as follows:
Is it possible to programatically show the tooltip of the second chart when hovering on the first chart - via chart 1's DataHover event?
EDIT
The info on the second chart is for Relative Strength Index. It is usually presented at the bottom of the chart. For this reason I made it a separate chart.
Although not an answer to my question, here is what I did. A now deleted comment asked why there are two charts. When I did it like that initially, the charts were over each other.
So I simply went back to that, and applied a scaling factor. 20% of the chart are is fine for the RSI, and as RSI is always calculated out of 100, I set the axis max value to 500% as follows:
chartMain.AxisY.Add(new Axis
{
MaxValue = 500,
MinValue = 0,
IsMerged = true,
Position = AxisPosition.RightTop,
ShowLabels = false,
Sections = new SectionsCollection
{
new AxisSection
{
SectionWidth = m_TradeManager.Settings.RSIThreshold,
Fill = new System.Windows.Media.SolidColorBrush
{
Color = System.Windows.Media.Color.FromRgb(254,132,132),
Opacity = .4
}
}
}
});
The end result is this:

Align two charts-areas one on top of the other [duplicate]

I have one Chart and three ChartArea that are aligned in view, zoom, cursor:
this is my related previous post. All things works well except that the three ChartArea are not aligned at the beginning. Following an image of the problem:
I think it depends from the digit's number of Y values axis. From some research I try the following configuration:
// selezione e zoom
dlChart.ChartAreas[VOLTAGE_AREA].CursorX.Interval = 1;
dlChart.ChartAreas[VOLTAGE_AREA].CursorX.IsUserEnabled = true;
dlChart.ChartAreas[VOLTAGE_AREA].CursorX.IsUserSelectionEnabled = true;
// generale
dlChart.ChartAreas[VOLTAGE_AREA].AxisX.LabelStyle.Format = "dd/MM/yy - HH:mm:ss.fff";
dlChart.ChartAreas[VOLTAGE_AREA].AxisX.ScaleView.Zoomable = true;
dlChart.ChartAreas[VOLTAGE_AREA].AxisY.LabelStyle.Format = "D5";
In witch the last row:
dlChart.ChartAreas[VOLTAGE_AREA].AxisY.LabelStyle.Format = "D5";
should specifies always five digits. This mitigate in some way the problem but it doesn't desappers. Furthermore with this row the program starts to throws very lots exceptions of form below any time I scroll the graph:
Generate exception: 'System.FormatException' in mscorlib.dll
Does anyone knows the solution for this problem? Thanks in advance.
You may want to take control of the size of the InnerPlotPosition.
(But Baddack's solution is simpler and more flexible!)
Here is an example:
After setting up a Chart with three CharAreas, setting Minima and Maxima as well as adding one DataPoint to each we get this :
Your issue is showing clearly.
After setting the InnerPlotPosition to a fixed percentage it looks like this:
Here is how to set the InnerPlotPosition size:
ca1.InnerPlotPosition = new ElementPosition(10, 5, 80, 90);
ca2.InnerPlotPosition = new ElementPosition(10, 5, 80, 90);
ca3.InnerPlotPosition = new ElementPosition(10, 5, 80, 90);
Note that both ChartArea.Position and ChartArea.InnerPlotPosition are called 'Position' but really are areas of percentages referring to the respective containers!
So my example has a Left distance of 10%, a Top space of 5% and Width of 80% and Height of 90%. Which leaves 10% space at the Bottom and 5% at the Right. Note: All are referring to the ChartAreas not the ClientArea of the Chart! (Which are still at Auto, which maximizes the size.)
This was my initial setup:
ChartArea ca1 = chart.ChartAreas[0];
ChartArea ca2 = chart.ChartAreas[1];
ChartArea ca3 = chart.ChartAreas[2];
Series s1 = chart.Series[0];
Series s2 = chart.Series.Add("Series2");
Series s3 = chart.Series.Add("Series3");
s2.ChartArea = ca2.Name;
s3.ChartArea = ca3.Name;
s1.Points.AddXY(1, 7);
s2.Points.AddXY(1, 777);
s3.Points.AddXY(1, Math.PI);
Have you tried using the chart area alignment options? I would try something like:
//define inner plot position of the chart areas
dlChart.ChartAreas[0].InnerPlotPosition.Auto = true;
dlChart.ChartAreas[1].InnerPlotPosition.Auto = true;
dlChart.ChartAreas[2].InnerPlotPosition.Auto = true;
//set our second chart area's alignments to match our first chart area
dlChart.ChartAreas[1].AlignmentOrientation = AreaAlignmentOrientations.Vertical;
dlChart.ChartAreas[1].AlignmentStyle = AreaAlignmentStyles.All;
dlChart.ChartAreas[1].AlignWithChartArea = dlChart.ChartAreas[0].Name;
//set our third chart area's alignments to match our first chart area
dlChart.ChartAreas[2].AlignmentOrientation = AreaAlignmentOrientations.Vertical;
dlChart.ChartAreas[2].AlignmentStyle = AreaAlignmentStyles.All;
dlChart.ChartAreas[2].AlignWithChartArea = dlChart.ChartAreas[0].Name;

How to separate two series by displaying Line between them in Column chart C#?

I have 2 series (2016 and 2017) in column chart and all datapoints values are showing fine. but I need to differentiate two series values by showing thick border line between two series.
because , now it seems to combining the 2017 values with 2016 series values since no separator line not there.
FYI.
EDIT:
After used vertical line in my column chart the output as like below,
But i need only one Line that should present between the two series .
how do i remove other lines.
Finally , Got the expected Output.
Thanks in advance.
var series = Mainchart.Series[0]; //series object
var chartArea = Mainchart.ChartAreas[series.ChartArea];
chartArea.AxisX.StripLines.Add(new StripLine
{
BorderDashStyle = ChartDashStyle.Solid,
BorderColor = Color.Black,
Interval = 0, // to show only one vertical line
IntervalOffset = 1.5, // for showing Vertical line between 2 series
IntervalType = DateTimeIntervalType.Years // for me years
});
You may use StripLine:
StripLine limit_lower_strip = new StripLine();
limit_lower_strip.Interval = 0;
limit_lower_strip.IntervalOffset = v1_lower;
limit_lower_strip.StripWidth = 0.0;
limit_lower_strip.BorderColor = Color.FromArgb(100, Color.Red);
limit_lower_strip.BorderDashStyle = ChartDashStyle.Solid;
limit_lower_strip.BorderWidth = 5;
chart1.ChartAreas[0].AxisX.StripLines.Add(limit_lower_strip);

How do I add additional series to a Excel Chart using C#

I am trying to add an additional data series to the chart this shows CPU threshold, I can get the range and create the graph with out the threshold on it, but I don't know how to add the threshold value to the chart.
do I need to create another chart object? can I use the existing and just add teh new range in?
How are you creating the chart? -- see code below.
Is this chart already created in the excel file, and you want to modify the chart in the excel file? yes the chart is already in a Excel file.
Excel.ChartObjects sCPUChart;
Excel.ChartObject sCPUChartObjects;
sCPUChart = sDBSheet.ChartObjects(Type.Missing);
sCPUChartObjects = sCPUChart.Add(49, 15, 360, 215);
Excel.Chart sChartCPU;
sChartCPU = sCPUChartObjects.Chart;
sChartCPU.SetSourceData(cpuChartRange, Missing.Value);
sChartCPU.ChartWizard(Source: cpuChartRange, Gallery: Excel.XlChartType.xlLine, Format: 2, HasLegend: true);
sChartCPU.Location(Excel.XlChartLocation.xlLocationAsObject, sDBSheet.Name);
//CPU Chart Axis
Excel.Axis xSChartCPUAxis;
xSChartCPUAxis = sChartCPU.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
Excel.Axis ySChartCPUAxis;
ySChartCPUAxis = syChartCPU.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary);
ySChartCPUAxis.HasMajorGridlines = true;
ySChartCPUAxis.MaximumScaleIsAuto = true;
//Set Summary CPU Series
Excel.Series sCPUSeries = sChartCPU.SeriesCollection(1);
sCPUSeries.Name = "CPU";
//-------
// this is where I am having my issue
//I don't know how to add the threshold line to the graph with the existing graph being displayed
//sChartCPU.set_HasAxis(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlSecondary, true);
//summaryChartCPU.SetSourceData(summaryMemThreshold, Type.Missing); -- things break
//-------
I have now done the following:
Excel.SeriesCollection threshold = sChartCPU.sseriesCollection();
Excel.Series line = threshold.NewSeries();
line.Formula = "=SERIES(Summ!$D$54,Summ!$C$55:$C$56,Summ!$D$55:$D$56)";
line.ChartType = Excel.XlChartType.xLScatterLinesNoMarkers;
when the threshold line is created I have the following
the values I have in cells D54 - threshold
C55 = 0
C56 = 1
D55 = 75
D56 = 75
I don't know how to remove the 2 additional axis that appear in chart
If I comment out the line.ChartType, then the axis is correct but I only get one threshold data point ?? I don't understand why.
var series = (SeriesCollection) yourChart.SeriesCollection();
var line = series.NewSeries();
line.Name = "CPU Threshhold";
//line.Values = ...;
//line.XValues = ...;
//formatting
Here's the solution I found to the OP's question of how to remove the secondary axes:
Excel.SeriesCollection threshold = sChartCPU.sseriesCollection();
Excel.Series line = threshold.NewSeries();
// line.Formula = "=SERIES(Summ!$D$54,Summ!$C$55:$C$56,Summ!$D$55:$D$56)";
// instead of setting the Formula, I set the series values
line.Values = "='Summ!'$D$55:$D$56";
line.XValues = "='Summ!'$C$55:$C$56";
line.ChartType = Excel.XlChartType.xlXYScatterLinesNoMarkers;
// creates Axis objects for the secondary axes
Excel.Axis YAxis2 = (Excel.Axis)sChartCPU.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlSecondary);
Excel.Axis XAxis2 = (Excel.Axis)sChartCPU.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlSecondary);
// remove the major and minor tick marks from the secondary (top) x-axis
XAxis2.MajorTickMark = Excel.XlTickMark.xlTickMarkNone;
XAxis2.MinorTickMark = Excel.XlTickMark.xlTickMarkNone;
// change the secondary x-axis max range to 1.0 so the bar will go all the way to the right side
XAxis2.MaximumScale = 1.0;
// delete the secondary x-axis labels
XAxis2.TickLabels.Delete();
// I chose to delete the secondary y-axis so the line would graph on the primary axis scale
YAxis2.Delete();

Categories

Resources