Forum Discussion
Scatter plot with different marker shapes and colours
No, the macro changes the shape of the markers according to the field.
The macro can handle any number of data rows, with any number of groups, and currently up to 6 fields (although that could be expanded to 9 if required).
Thank you Hans, how can I add this macro into my file with my real data?
- HansVogelaarDec 12, 2022MVP
Open your own workbook.
Press Option+F11 to activate the Visual Basic Editor.
Select Insert > Module to create a new code module.
Copy the following code into the module:
Sub CreateChart() Dim wsh As Worksheet Dim r0 As Long Dim r As Long Dim m As Long Dim s As Long Dim cho As ChartObject Dim cht As Chart Dim ser As Series Dim pnt As Point Dim fld As Long Dim x As Double Dim y As Double Dim grp As String Dim arr As Variant Dim n As Long Dim i As Long Dim f As Boolean Application.ScreenUpdating = False arr = Array(xlMarkerStyleCircle, xlMarkerStyleDiamond, _ xlMarkerStyleSquare, xlMarkerStyleTriangle, _ xlMarkerStyleStar, xlMarkerStylePlus) Set wsh = ActiveSheet m = wsh.Range("A" & wsh.Rows.Count).End(xlUp).Row wsh.Range("A1:D" & m).Sort Key1:=wsh.Range("D1"), Header:=xlYes Set cho = wsh.ChartObjects.Add( _ Left:=wsh.Range("F2").Left, _ Top:=wsh.Range("F2").Top, _ Width:=Range("F2:L2").Width, _ Height:=Range("F2:F15").Height) Set cht = cho.Chart cht.ChartType = xlXYScatter ReDim arr2(1, n) For r = 2 To m + 1 If Range("D" & r).Value <> Range("D" & r - 1).Value Then If r0 > 0 Then Set ser = cht.SeriesCollection.NewSeries ser.Name = grp ser.XValues = wsh.Range("B" & r0 & ":B" & r - 1) ser.Values = wsh.Range("C" & r0 & ":C" & r - 1) For s = r0 To r - 1 Set pnt = ser.Points(s - r0 + 1) fld = wsh.Range("A" & s).Value f = False For i = 1 To n If arr2(0, i) = fld Then pnt.MarkerStyle = arr2(1, i) f = True Exit For End If Next i If Not f Then n = n + 1 ReDim Preserve arr2(1, n) arr2(0, n) = fld arr2(1, n) = arr(n - 1) pnt.MarkerStyle = arr2(1, n) End If Next s End If r0 = r grp = Range("D" & r).Value End If fld = wsh.Range("A" & r).Value Next r Application.ScreenUpdating = True End Sub
You can now close the Visual Basic Editor.
Back in Excel, save the workbook as a macro-enabled workbook (*.xlsm).
You can run the macro as follows:
- Press Option+F8 to activate the Macros dialog.
- Select CreateChart in the list of macros.
- Click Run.
- You can also click Options and assign a keyboard shortcut to the macro.
P.S. Make sure that you allow macros when you open the workbook.
- Calli99Dec 12, 2022Copper Contributor
Yes they are, but I have 25 rows (including row 1 as header)
- HansVogelaarDec 12, 2022MVP
Are your real data also in columns A to D, starting in row 2 (headers in row 1)?