我用VBA代码绘制了XY散点图。但是我无法更改水平轴标签。水平轴标签可以更改为文本吗?如果是,我该如何使用数组进行更改。
这是我使用VBA创建的XY散点图:XY Scatter chart
我想使用数组将水平标签从1,2,3,4(如图所示)更改为A,B,C,D。非常感谢!
编辑: 我的数据表: Data table
VBA宏代码:
Sub plot_test3()
Dim ws2 As Worksheet
Dim i, j, c, m, n, a, lrow As Long
Dim frist_code, frist_value, frist_name, frist_date As Variant
Dim xychart As Chart
Set ws2 = Worksheets("Sheet3")
i = 1: j = 1: a = 1: k = 1: p = 2
c = 4: lrow = 6: m = 2: n = 2
ws2.Activate
ReDim frist_code(1 To lrow - 1)
ReDim frist_value(1 To lrow - 1)
ReDim frist_name(0)
ReDim frist_date(1 To lrow - 1)
Set xychart = ws2.Shapes.AddChart2(Left:=0, Top:=0, Width:=400, Height:=300).Chart
For j = 1 To c
For i = 1 To lrow - 1
frist_value(i) = ws2.Cells(m, n)
frist_code(i) = k
frist_name(0) = ws2.Cells(1, n)
frist_date(i) = ws2.Cells(m, 1).Value2
m = m + 1
Next i
xychart.SeriesCollection.NewSeries
xychart.ChartType = xlXYScatter
With xychart.SeriesCollection(a)
.Name = frist_name(0)
.Values = frist_value
.XValues = frist_code
.MarkerSize = 15
.MarkerStyle = 2
End With
a = a + 1
n = n + 1
m = 2
k = k + 1
Next j
xychart.Axes(xlCategory).TickLabelPosition = xlLow
xychart.SetElement (msoElementLegendBottom)
End Sub
答案 0 :(得分:0)
XY散射不足以实现此目的。 XY需要在X轴上连续的值,因此与命名值不兼容。
要获得所需的标签,必须使用离散型图表,例如折线。
但是为此,您不能在同一X值中包含多个值。您可以:
编辑:第二个选项的代码:
以下代码将生成所需的图表。注释图表不是交互式的,即,在电子表格中更改值不会更改图表!
Sub Plot_Chart()
Dim v(), r As Long, c As Long
'Create and use chart
With ActiveSheet.Shapes.AddChart(xlLineMarkers).Chart
'Clear all series and legend
While .SeriesCollection.Count
.SeriesCollection(1).Delete
Wend
.Legend.Delete
'Iterate through rows and columns of data
For r = 2 To Selection.Rows.Count
For c = 1 To Selection.Columns.Count
'Create series and use it
With .SeriesCollection.NewSeries 'chart.SeriesCollection
'Create data with single valid point
ReDim v(1 To Selection.Columns.Count)
v(c) = Selection(r, c)
.Values = v
End With
Next
Next
'Set and format X-Axis
.SeriesCollection(1).XValues = Selection.Rows(1).Value
With .Axes(xlCategory)
.MajorTickMark = xlNone
.TickLabelPosition = xlLow
End With
'Format series
For c = 1 To .SeriesCollection.Count
.SeriesCollection(c).MarkerStyle = xlMarkerStyleDiamond
.SeriesCollection(c).MarkerSize = 7
Set dbg = .SeriesCollection(c).Format.Fill
.SeriesCollection(c).Format.Fill.ForeColor.ObjectThemeColor = (c - 1) Mod Selection.Columns.Count + 5
.SeriesCollection(c).Format.Line.ForeColor.ObjectThemeColor = (c - 1) Mod Selection.Columns.Count + 5
Next
End With
End Sub