Pie chart code in vb.net - vb.net

I have used this code for pie chart in vb.net. This is working fine but one problem is when one of the yValue is 0 it is showing 0 in the pie chart.
I want to know how to stop showing 0 value in the pie chart and what I have to correct in the code so that it does not 0 value.
Dim yValues As Double() = {str_total, Totalmale.ToString, Totalfemale.ToString, Totalengagedact.ToString, Totalmaterial.ToString, Totalpattaholder.ToString} ' Getting values from Textboxes
Dim xValues As String() = {"Total Beneficiary", "Male", "Female", "Engaged in same activity before", "Material Support received", "Patta holder"} ' Headings
Dim seriesName As String = Nothing
' Note 1 : Clear chart before fill - VERY IMPORTANT and can generate exception if you are generating
' multiple charts in loop and have not included below lines !
' Note 2 : Chrt variable here is the Name of your Chart
Chart1.Series.Clear()
Chart1.Titles.Clear()
' Give unique Series Name
seriesName = "ChartInv"
Chart1.Series.Add(seriesName)
' Bind X and Y values
Chart1.Series(seriesName).Points.DataBindXY(xValues, yValues)
' Define Custom Chart Colors
Chart1.Series(seriesName).Points(0).Color = Color.MediumSeaGreen
Chart1.Series(seriesName).Points(1).Color = Color.PaleGreen
Chart1.Series(seriesName).Points(2).Color = Color.LawnGreen
Chart1.Series(seriesName).Points(3).Color = Color.Blue
Chart1.Series(seriesName).Points(4).Color = Color.Red
Chart1.Series(seriesName).Points(5).Color = Color.Yellow
' Define Chart Type
Chart1.Series(seriesName).ChartType = DataVisualization.Charting.SeriesChartType.Pie
Chart1.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
' If you want to show Chart Legends
Chart1.Legends(0).Enabled = True
' If you don't want to show data values and headings as label inside each Pie in chart
'Chart1.Series(seriesName)("PieLabelStyle") = "Disabled"
'Chart1.Series("ChartInv").IsValueShownAsLabel = False
' If you want to show datavalues as label inside each Pie in chart
Chart1.Series(seriesName)("PieLabelStyle") = "Enabled"
Chart1.Series("ChartInv").IsValueShownAsLabel = True

Take the Xvalues and Yvalues after calculating the 0
for example
consider variable x, and the value for this variable is 0. in that case dont add its reference at either xvalues or Yvalues

Related

How can I add values from a datagridview into a pie chart in vb.net?

I would like to represent 2 values from a datagridview into a pie chart. These values are integers and have already been displayed in the datagridview. I just need those values to be displayed in a pie chart.
Here is what I've tried:
For Count As Integer = 0 To DataGridView1.Rows.Count - 2
Chart1.Series(0).Points.Add(DataGridView1.Item(0, Count).Value, DataGridView1.Item(1, Count).Value)
Chart1.Series(1).Points.Add(DataGridView1.Item(0, Count).Value, DataGridView1.Item(1, Count).Value)
Next
This creates a loop to insert all values from the datagridview into the chart. The problem is that when it runs, the chart does not display these two integers.
you might want to get the id of the selected item in the Datagridview first, and use a datable for its record to display in chart, that should do the trick
Declare the x and y values and the series of the pie chart.
Dim series As String = "Time"
Dim yval As Double() = { x, y }
Dim xval As String() = {"Time Studying", "Time Not Studying"}
Retrieve the values from the data grid view.
For Count As Integer = 0 To DataGridView1.Rows.Count - 2
x = DataGridView1.Item(0, Count).Value
y = DataGridView1.Item(1, Count).Value
Next
Clear the graph values
Chart1.Series.Clear()
Chart1.Titles.Clear()
Plot values into chart.
Chart1.Series.Add(series)
Chart1.Series(series).Points.DataBindXY(xval, yval)
Chart1.Series("Time").IsValueShownAsLabel = True
Chart1.Series(series).Points(0).Color = Color.LightSkyBlue
Chart1.Series(series).Points(1).Color = Color.Orange
Chart1.Series(series).ChartType = SeriesChartType.Pie

Is there a way to plot a line graph with integer x values but label each point on the x axis with a string?

I'm producing a line graph and I'm plotting points according to x and y values using points.addxy(X, Y). However the xvalues are plotted through regular intervals which I want to have labeled below the axis. My code is below:
Dim AllRaceArray() As String = GetAllRaceArray() 'Array of The race names in date order
Dim RaceIDs() As Integer = GetAllRaceID() 'Array Of The Race IDs Paralell to the above array
Dim Xnum As Integer = AllRaceArray.Length
Dim Interval As Integer = Math.Floor(Chart1.Size.Width / Xnum)
Chart1.Series.Clear()
For i = 0 To 3
If CompareSlotEmpty(i) = False Then
Chart1.Series.Add(i & CompPaddler(i).Name)
Chart1.Series(i).ChartType = SeriesChartType.Line
Chart1.Series(i).XValueType = ChartValueType.String
Chart1.Series(i).BorderWidth = 2
Chart1.Series(i).MarkerStyle = DataVisualization.Charting.MarkerStyle.Circle
Chart1.Series(i).MarkerSize = 8
For p = 0 To Xnum - 1
For q = 0 To CompPaddler(i).RacePoints.Length - 1
If CompPaddler(i).RacePoints(q).RaceID = RaceIDs(p) Then
Chart1.Series(i).Points.AddXY(Interval * p, CompPaddler(i).RacePoints(q).Points) ' this point plot creates the correct ordering
Chart1.Series(i).Points.AddXY(AllRaceArray(p), CompPaddler(i).RacePoints(q).Points) ' this point plot creates the correct labels
End If
Next
Next
End If
' EDIT
' This below Section has now been added but nothing appears below the axis at all now
For t = 0 To Chart1.Series(i).Points.Count - 1
Chart1.Series(i).Points(t).AxisLabel = AllRaceArray(t)
Next
'EDIT
Next
As annotated above One chart series creates the correct looking graph (http://tinypic.com/r/sobwbc/9) but x axis labels. Then the second plotter plots the correct labels but the ordering and scale gets messed up (http://tinypic.com/r/2w2g5s4/9).
TLDR: How to I change the xAxis Labels to strings that line up with regularly interval points?
Edit: I have added a loop to change the .axislabel but now nothing shows below the axis

Excel Chart - How to draw discontinuous series in VBA without range reference

Excel 2010.
Issue : I need to plot a *single* *discontinuous* series in a XY-scatter chart *via VBA* without referencing a range in the sheet.
It is easy to achieve that when the Yvalues are laid-out in a sheet range, by inserting blank values at the discontinuities ; as long as one selects 'Show empty cells as: Gaps' in Select Data > Hidden and Empty Cells. Here is an example (the Series2 in red is the one that matters) :
So I was trying to reproduce the same via VBA :
Sub addDiscountinuousSingleSeries()
Dim vx As Variant, vy As Variant
Dim chrtObj As ChartObject, chrt As Chart, ser As Series
Set chrtObj = ActiveSheet.ChartObjects("MyChart"): Set chrt = chrtObj.Chart
Set ser = chrt.SeriesCollection.NewSeries
vx = Array(0.3, 0.3, 0.3, 0.7, 0.7, 0.7)
vy = Array(-1, 1, vbNullString, -1, 1, vbNullString)
'vy = Array(-1, 1, CVErr(xlErrNA), -1, 1, CVErr(xlErrNA)) 'doesn't work either
'vy = Range(RANGE_YVALUES_WITH_BLANK) 'this would work, but I do not want to reference a range
chrt.DisplayBlanksAs = xlNotPlotted 'VBA equivalent to 'Show empty cells as: Gaps'
With ser
ser.Name = "VBA Series"
.XValues = vx
.Values = vy
End With
End Sub
But the blank values in the vy array seems to be ignored and the two vertical bars are now connected, which I am trying to avoid (green series).
I know that I could delete the middle line programmatically, but in the real-life problem I am trying to solve it would not be the right solution (too complex, too slow).
My question : is there a way to specify the series' .Values array to get the expected behavior and get a gap between the two vertical green segments in vba (with only one series and no reference to a sheet range)?
You could just format the lines you don't want. Maybe not the prettiest way, but it'd achieve what your after.
ser.Points(3).Format.Line.Visible = msoFalse
ser.Points(4).Format.Line.Visible = msoFalse
ser.Points(6).Format.Line.Visible = msoFalse
Or:
For i = 1 To ser.Points.Count
If i <> 1 Then k = i - 1 Else k = i
If ser.Values(i) = 0 Or ser.Values(k) = 0 Then
ser.Points(i).Format.Line.Visible = msoFalse
End If
Next

Format datatable values in VBA

Currently working on a vba script that makes charts automatically. I would like to add a datatable which is done using: .HasDataTable = True
However I would like to show the values of series as percentages. Currently the value is defined as a Double containing all the values but not the right formatting. Using Format() or FormatPercent() will give the right values but returned in a String. This works for the datatable but not for the chart itself since it doesn't recognize the values anymore.
My question comes down to whether it is possible to show the values as percentages in both the datatable and the chart? Without VBA it is easily done by formatting the data in the cells itself. The problem is that for formatting a String is returned but for the graph Integers or Doubles are needed.
Below is part of the code. If I dim Ratio as String and use FormatPercent() I get the requested formatting but then the values in Ratio ar no longer doubles so it doesn't give the required chart.
Dim Ratio() As Double
Dim labels() As String
ReDim Ratio(1 To Height)
ReDim labels(1 To Height)
For Each Column In sArray
labels(i) = Sheets(DataSheetName).Cells(LabelsRow, Column)
Ratio(i) = Math.Round(Sheets(DataSheetName).Cells(LabelsRow + 3, Column), 2)
i = i + 1
Next Column
Set myChtObj = Sheets(DrawSheetName).ChartObjects.Add(Left:=Left, Width:=Width, Top:=Top, Height:=HeightGraph)
Dim srsNew1 As Series
' Add the chart
With myChtObj.Chart
.ChartArea.Fill.Visible = False
.ChartArea.Border.LineStyle = xlNone
.PlotArea.Format.Fill.Solid
.PlotArea.Format.Fill.Transparency = 1
.HasTitle = True
.ChartTitle.text = Title
.HasLegend = False
.Axes(xlValue).TickLabels.NumberFormat = "0%"
.Axes(xlCategory, xlPrimary).HasTitle = False
'add data table
.HasDataTable = True
' Make Line chart
.ChartType = xlLine
' Add series
Set srsNew1 = .SeriesCollection.NewSeries
With srsNew1
.Values = Ratio
.XValues = labels
.Name = "Ratio"
.Interior.Color = clr3 'RGB(194, 84, 57)
End With
End With

How to assign XValues for excel chart using VBA

I have this VBA function for drawing charts in Excel 2013:
Sub DrawChart2(obj_worksheetTgt As Worksheet, ByVal XLabels As Range, ByVal DataValues As Range, ByVal chartTitle As String, a As Integer, b As Integer)
'
'obj_worksheetTgt - Object worksheet on which to be placed the chart
'XLabels - Data range for X labels
'DataValues - Data range for Y values
'chartTitle - Chart title
'a - left border position of chart in pixels
'b - top border position of chart in pixels
With obj_worksheetTgt.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered
Set .SeriesCollection(1).XValues = XLabels ' Here is the error
Set .SeriesCollection(1).Values = DataValues
.Legend.Position = -4107
.HasTitle = True
.chartTitle.Text = chartTitle
.chartTitle.Font.Size = 12
With .Axes(1).TickLabels
.Font.Size = 8
.Orientation = 90
End With
End With
End With
End Sub
I call the function this way:
ChartsWorksheet = "Summary"
Queryname = "query1"
chartTitle = "Values"
With .Worksheets("LastDayData").ListObjects(Queryname)
Set chart_labels = .ListColumns(2).DataBodyRange
Set chart_values = .ListColumns(6).DataBodyRange
End With
Call DrawChart2(.Worksheets(ChartsWorksheet), chart_labels, chart_values, chartTitle, 10, 10)
And I receive an error:
Runtime Error '1004':
Invalid Parameter
When I click debug it marks the row "Set .SeriesCollection(1).XValues = XLabels" in the function above.
In the documentation is written:
The XValues property can be set to a range on a worksheet or to an
array of values, but it cannot be a combination of both
So it should be able to take the given range as values for XValues, but I can't understand why this error appears.
Before you can set the Values and XValues of a series, you will need to add the series first. This is simple to do using the SeriesCollection.NewSeries method as show below:
With ActiveSheet.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered
' need to add the series before you can assign the values/xvalues
' calling the "NewSeries" method add one series each time you call it.
.SeriesCollection.NewSeries
' now that the series is added, you may assign (not set) the values/xvalues
.SeriesCollection(1).XValues = XLabels
.SeriesCollection(1).Values = DataValues
End With
End With
You cannot use named ranges for .XValues or .Values, but you can change the .Formula property by replacing the series formula
For more information on editing the series formula see http://peltiertech.com/change-series-formula-improved-routines/
Note of caution, there is a bug in Excel 2013 that prevents you from using named ranges starting with "R" or "C" when using VBA to change the series formula; see http://answers.microsoft.com/en-us/office/forum/office_2013_release-excel/named-range-use-in-chart-series-formulas-causes/c5a40317-c33f-4a83-84db-0eeee5c8827f/?auth=1&rtAction=1466703182593