【发布时间】:2015-12-16 17:42:07
【问题描述】:
我正在尝试使用 Visual Basic 创建散点图,y 轴是数值,x 轴是日期。目的是让情节包含多个系列。以下是相关代码:
ActiveWorkbook.Charts.Add
ActiveChart.ChartArea.Select
With ActiveChart
.ChartType = xlXYScatter
.HasTitle = True
.ChartTitle.Text = "Time Trend of Data"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dates"
.Axes(xlCategory, xlPrimary).CategoryType = xlTimeScale
.Axes(xlCategory, xlPrimary).TickLabels.NumberFormat = "m/d/yy;@"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Total Time"
.Legend.Position = xlLegendPositionBottom
End With
ActiveSheet.Move After:=Sheets(ActiveWorkbook.Sheets.count)
ActiveSheet.Name = "Time Trend " + CStr(currTT) ' This is just to make sure the new sheet does not have the same name
生成一些数据后,我尝试用循环绘制它。我使用的数组是 chartLabels - 这是每个系列的名称,chartData - 每个系列都有多个数据点的 3d 数组series 和 xval 和 yval - 从 chartData 数组构建的数组,它们相互绘制:
For j = 0 To UBound(chartLabels)
If IsEmpty(chartLabels(j)) Then Exit For
Erase xval
Erase yval
ReDim Preserve xval(0 To 0)
ReDim Preserve yval(0 To 0)
xval(0) = chartData(1, j, 0)
yval(0) = chartData(2, j, 0)
For i = 0 To UBound(chartData, 3) - 1
If Not IsEmpty(chartData(2, j, i + 1)) Then
ReDim Preserve xval(0 To i + 1)
ReDim Preserve yval(0 To i + 1)
xval(i + 1) = chartData(1, j, i + 1)
yval(i + 1) = chartData(2, j, i + 1)
End If
Next
MsgBox (Join(xval, " || "))
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(j + 1).XValues = xval
ActiveChart.SeriesCollection(j + 1).Values = yval
ActiveChart.SeriesCollection(j + 1).Name = main.chartLabels(j)
Next
包含 MsgBox 语句以查看我作为 XValues 传递给我的散点图的数组。 第一个系列的数组输出如下所示:
所有这些值都是日期格式。创建的系列数量各不相同。此外,每个系列中的数据点数量很大程度上取决于用户选择的选项。但是,散点图上生成的输出如下所示:
图表上的所有内容都是正确的,除了 xaxis 被缩放到其各自系列中每个数据点的位置,而不是实际日期(即 1/0/00 在日期格式中实际上是 0 而 3/10/00 是70,因为大约有 70 个数据点)。
我尝试使用 xlCategoryScale 和 xlAutomaticScale 作为我的 CategoryType。我已经尝试在我的每个 xval 以及 CStr() 上使用 CDate()。我尝试为 XValues 输出不同的数组。没有任何效果。
我怀疑这个问题与我试图绘制多个系列数据的事实有关。但是,如果有人能告诉我实际问题和/或解决这个问题的方法,我将非常感激。提前谢谢!
【问题讨论】:
-
以
.ChartType=xlLineMarkers开头而不是scatter? -
@MacroMarc 出于某种原因,它不会将其作为参数。我不确定为什么。我最终通过使 xvalues 加倍来解决它。我不知道为什么会这样,但我没有抱怨。还是谢谢!
标签: vba excel scatter-plot