Excel Histogram - Distribution Line - vba

I want to make a histogram in excel which is easy using data analytics toolbox. If I wanna make it automatic in vba I can use this post to get the bins automatically and then set the reference ranges.
Problem arises when I want to have the smoothed distribution line. If I change the chart type to scatterplot smooth line, it will connect the columns height to each other which will be like the blue line in this picture:
But what I really want is something like the purple line (i.e. a normal distribution overlaid on top of the histogram). This is not be desired if the data is skewed or generally have a different distribution. Is there anyway to make this overlay automatic in reference to distribution of the data? (Something like what R does) Preferably using macro, but any input would be great.

I added a Trendline to my chart (in red) and then formatted the Trendline as "Polynomial" and it achieved an effect similar to what you have.
Here's some code to achieve this programatically:
Sub AddPolynomialTrendline()
Dim chrt As Chart
Dim chrt_obj As ChartObject
Dim trend As Trendline
For Each chrt_obj In ActiveSheet.ChartObjects
If chrt_obj.Name = "Chart1" Then
With chrt_obj.Chart
'the number after xlPolynomial is the order, which can be from 2 to 6
Set trend = .SeriesCollection(1).Trendlines.Add(xlPolynomial, 6)
End With
End If
Next chrt_obj
End Sub
Hope this helps!

Related

SeriesCollection array size in PPT VBA

I am trying to add data labels to all my series in a bar chart but the amount of series varies from chart to chart because this is a function used for many charts. So, I used a For Loop to add them, but I need to determine the size of the SeriesCollection array. Would there be a function that would do so? When I try to use .Size it gives me an error.
Below is what I tried:
With Chart
For i = 1 To .SeriesCollection.Size
.SeriesCollection(i).Points(i).HasDataLabel = True
Next i
End With
Some of the stuff in the Chart object model isn't properly hooked up to Intellisense. You'll notice that you get no suggestions when you type .SeriesCollection.
.SeriesCollection.Count will give you what you're after, I think.

Reinstate Excel chart default resizing behaviour using VBA

I am looking for a way to reinstate the default/native resizing behaviour of a chart in Excel 2010 once it has been disabled (e.g. by manipulating the chart with VBA).
Now I haven't been able to find anything anywhere about the behaviour I have in mind, so I am going to assume that it needs detailed explanation.
Input and select random numerical data into 4-5 cells in Excel, and insert a new Clustered Columns chart. You need to see a the chart's plot area. Now select the chart, and get the PlotArea.Top value with the following line
ActiveChart.PlotArea.Top
If you haven't touched the chart, this should return a value of 7. Now use one of the chart's handlebars to resize the chart vertically, and use the same command line again.
activechart.plotarea.top
Notice how the value returned is still 7. Now set this property to 7 in VBA.
ActiveChart.PlotArea.Top = 7
Again, grab one of the handlebars, resize the chart vertically and get the .top property again using:
ActiveChart.PlotArea.Top
Notice how the value has now changed. It will be either smaller or greater than 7 depending on whetehr you decreased or increased the size of the chart.
Once any element of a chart has been moved either manually or with VBA code, it loses this "absolute position" property and begins moving inside the ChartArea whenever the chart is resized. While some elements can be reset using .SetElement, this does not work for the Plot Area. For example, the following command lines do not reinstate the behaviour I am describing.
ActiveChart.SetElement msoElementPlotAreaNone
ActiveChart.SetElement msoElementPlotAreaShow
I do a lot of automated resizing of charts with VBA, and having the plot area move around by itself makes it a lot harder to predict the effect of resizing the chart and leads to inconstant results.
So back to the question: does anyone know of a way to reinstate this default behaviour, either for the entire chart, or at least specifically for the PlotArea?
Thanks in advance to anyone who may help!
Vincent
I ran into this when I manually resized the plot area and then when the legend is moved it did not resize the plot area at all.
I had tried to save my chart as a template (right click save as template in Excel 2013) but this still had the plot area manually set.
Therefore I would recommend keeping the auto-size behavior before saving a template, since the only way I know to re-set the chart auto-sizing behavior after it has been manually modified is to use a macro
Here is the macro I used to reinstate the auto-sizing behavior
Sub Macro1()
'
' this selects the chart based on the chart name
ActiveSheet.ChartObjects("Chart 4").Activate
' this selects the plot area
ActiveChart.PlotArea.Select
' this clears any custom formatting such as borders or fill colors
ActiveChart.PlotArea.ClearFormats
' this resets the auto-sizing behavior after plot area manually re-sized
ActiveChart.PlotArea.Position = xlChartElementPositionAutomatic
End Sub
References
Why plot area does not expand after clearing series legend?
Excel Chart Plot Area Auto Size - ExcelBanter

Attaching a Textbox to a point or line on a chart in Excel/VBA

I was wondering how to attach a textbox to a point or line in an Excel chart for the macro I am working on. I have been using the .AddTextbox method such as
.Shapes.AddTextbox(msoTextOrientationHorizontal, 150, 250, 100, 15) _
.TextFrame.Characters.Text = "Temperature"
But I have to then manually drag the textbox over the line on the chart it is representing as the orientation is of the chart not the line. Is there a way to convert the line/point to a chart orientation which I could use as a variable? or another way? Possibly using the datalabel function, though I want to be able to customize one of the axis locations. Thanks
To solve your question you need to get the left & top position of two objects:
chart itself, which position is set in relation to top-left corner of sheet range area
point in series which position is set in relation to top-left corner of chart
Combination of both result with the following code (fixed parameters-required changes to your situation, could be more dynamic with loop)
Sub Add_Text_to_point()
Dim tmpCHR As ChartObject
Set tmpCHR = Sheet1.ChartObjects(1) 'put index of your chartobject here
'for first serie, for point 2nd here
'(change accordingly to what you need)
With tmpCHR.Chart.SeriesCollection(1).Points(2)
Sheet1.Shapes.AddTextbox(msoTextOrientationHorizontal, _
.Left + tmpCHR.Left, _
.Top + tmpCHR.Top, _
100, 15) _
.TextFrame.Characters.Text = "Temperature"
End With
End Sub
After result presenting the picture below.
Another option would be to use the data labels of Excel. I see two more elegant options:
Make a new data series with just one entry in your chart, give the series the coordinates and the name of the label you want to see. Now activate the marker option for the series (if not done already), right-click on the data point, click "add data labels". Now you'll see the y-Value of the point. By right-clicking again and choosing "Format Data Labels" you can change the text to the series name, also the position, the border, etc. are modifiable. Below an example with two data points. You could delete the second point, the line and the marker but like this you see how it works.
Similarly to the solution from KazJaw you can use the actual data points of your series for attaching custom data labels. This requires some coding, I used this for the chart named "Topview" and wrote percentages next to the data point
Sub Add_Text_to_data_points()
percentages(1) = 0.1
percentages(2) = 0.23
'.... further entries
chartNumber = findChartNumber("Topview")
collNumber = 12 ' index of the "points" series
Set tmpCHR = ActiveSheet.ChartObjects(chartNumber)
For i = 1 To tmpCHR.Chart.SeriesCollection(collNumber).Points.count
With tmpCHR.Chart.SeriesCollection(collNumber).Points(i)
If percentages(i) <> 0 Then
.DataLabel.Text = format(percentages(i), "0%")
End If
End With
Next
End Sub

Draw in a chart (not a chart object but a Chart) with vba

I'll try to be very precise with my problem but if you have any questions, please ask!
So basicelly I have a column A full of dates (from line 1 to line 80) and a column B full of values (stock prices, and also with the same range).
I have created a chart with this code :
Sub Chart()
Range(Cells(1, 1), Cells(80, 1))Select
Range(Selection, Selection.Offset(0, 1)).Select
Set rSource=selection
ActiveChart.SetSourceData Source:=rSource, PlotBy:=xlColumns
ActiveChart.Location Where:=xlLocationAsNewSheet
end sub
So this is not a chart object but a new chart on a new sheet (I say that because all the things I've read on this subject is dealing with chart objects and not with chart alone in a sheet).
Now what I need is to draw an horizontal line between two dates (a support line).
For example, I need to draw a line between 01/01/2013 (line 1) and 06/25/2013 (line 80).
The line has to stay at the same level on the y-axis (that's what we call an horizontal line :) ) at the level of the stock price of 01/01/2013.
I've tried that :
Sub supportline()
Dim CoordA As Variant
CoordA = [a1:b80]
ActiveChart.Shapes.AddLine(CoordA(1, 1), CoordA(1, 2), CoordA(80, 1), CoordA(80, 2)).Select
end sub
But the line isn't drawn where I want. I think there's a problem of scale but I can't figure out how to have the accurate coordinates.
Thank you very much for your time and your help
EDIT (06/11/2013)
I've simplified the data base to illustrate my problem : http://cjoint.com/?CFksHluf0VD I'm trying to make a line between the two dates (01/01/2013 and 16/01/2013)
If you download this file, you'll see in the VBA part : 1/ Test1 : I've tried to make a line to link 2 points of the chart : if you launch the sub you'll see that the line is drawn but at the wrong scale and wrong place 2/ Test 2: I've tried to make an horizontal line between two points but that doesn't work at all
Test 2 is what I need to do for my original project (an horizontal line which goes from one date to another with the same y-value)
ActiveChart.SeriesCollection(1).Select
With Selection.Format.Line
.Visible = msoTrue
//add line style etc
End with
Then use your select statement to choose which points you want joined.
If you look at this link, I'll think you'll find it most useful
VBA-Controlled Conditional Formatting of Line Chart Lines
http://peltiertech.com/WordPress/conditional-formatting-of-lines-in-an-excel-line-chart-using-vba/
Another question on Stack Overflow
Excel VBA - How do you set line style for chart series?
In response to your comments, please see the answer to this question. It offers some good explanation of using charts (in this case vb.net)
Chart: Show more value descriptions on X-Axis
And a link to MSDN re this
http://msdn.microsoft.com/en-us/library/system.windows.forms.datavisualization.charting.chart.aspx

Color Points (Bars) in Pivot Chart based on Row Labels (Axis Fields)

I'm trying to automate a process that so far I have been doing manually in Excel 2010. I create Pivot Charts often. One of the series on these charts is displayed as bars. I change the fill color of each bar based on one of the row labels of the pivot chart. For instance, if the row label = "GEO", I change the fill color of the bar to green.
I'm sure that it's possible to automate this process through VBA. Here's my code so far. When I run this macro, it stops at the first line of the If statement and gives this error. Compile error: Expected array. Can anyone give me some advice as to how to make this code work?
Sub By_Rig_PC_Coloring()
For i = 1 To ActiveChart.SeriesCollection(2).Points.Count
ActiveChart.SeriesCollection(2).Points(i).Select
If xlRowField("MFR") = "GEO" Then
Selection.Format.Fill.Forcolor.RGB = RGB(0, 176, 80)
End If
Next i
End Sub
As far as I know, you cannot access X axis labels associated with current Point. But this is a PIVOT chart, so you can use your pivot table to get the info you need.
Points are DataField's PivotItems, Series are ColumnFields and X labels are RowFields.
So SeriesCollection(2).Points(10) will be pvtYourPivotTable.ColumnFields(2).DataRange.Cells(10) (assuming that you have only one DataField, otherwise DataRange will be multi-column, and you'll have to adjust for that).
So once you have a cell in pivot table assosacietd with Point, the label will be located at Intersect(pvtYourPivotTable.RowFields("MFR").DataRange, pvtYourPivotTable.ColumnFields(2).DataRange.Cells(10).EntireRow. You can also use Offset or other method.
Here is another method of colouring chart bars based on X labels: Peltier Tech Blog without VBA.
Hope this helps.