VBA Chart Manipulation Slow - performance

I wrote some Excel VBA code that generates a scatterplot and changes a few properties of the chart. (Code is below for reference.) The code moves slowly through tasks like deleting the chart legend, removing horizontal/vertical gridlines, and changing the X and Y series. Excel's timer gives me the following duration for each task:
insert scatterplot: 0.01171875
delete series: 0
plot x vs y: 0.55859375
delete legend: 0.5703125
delete chart title: 0.66015625
remove grid: 1.3046875
format axes: 0
overall: 3.11328125
Removing the grid, changing the title, plotting the X and Y series, and deleting the legend seem to take a long time. I've googled for alternative ways to write the code, but haven't been able to find anything useful. The code works entirely as expected, except for the slow speed. Any ideas as to what's causing the bad performance, and how I can speed this up? Thanks in advance.
EDIT: I've already turned off screen updating while working with the chart. The chart is generated/formatted while a userform is open, if that makes any difference.
Here is the relevant snippet of code:
With ActiveChart
'Delete all series currently in plot
Do While .FullSeriesCollection.Count > 0
.FullSeriesCollection(1).Delete
Loop
'Plot Actual (Y) vs. Inverse Distribution (X)
.SeriesCollection.NewSeries
.FullSeriesCollection(1).XValues = "=" & tempSheetName & "!$C:$C"
.FullSeriesCollection(1).Values = "=" & tempSheetName & "!$A:$A"
'Delete legend
.Legend.Delete
'Delete chart title
.SetElement (msoElementChartTitleNone)
'Remove gridlines
.SetElement (msoElementPrimaryValueGridLinesNone)
.SetElement (msoElementPrimaryCategoryGridLinesNone)
'Format axes
Dim xAxis As Axis, yAxis As Axis
Set xAxis = .Axes(xlCategory)
Set yAxis = .Axes(xlValue)
With yAxis
'Title y axis "actual"
.HasTitle = True
.AxisTitle.Caption = "Actual"
'Add tick marks
.MajorTickMark = xlOutside
End With
With xAxis
'Title x axis by dist type
.HasTitle = True
.AxisTitle.Caption = dist.getDistType
'Add tick marks
.MajorTickMark = xlOutside
End With
End With

Without the data and machine specifics it can be hard to say why this is slow, although here are some alternatives to some of the code you have.
The first and foremost thing I'd change is not to Activate the chart. If you are creating the chart through code, do so but set it to a variable, eg Set wcChart = ThisWorkbook.Charts.Add. Then change With ActiveChart to With wcChart.
Also, delete the FullSeriesCollection and then delete the chart title, remove the gridlines and change the axes before filling up the new data. The chart manipulation should be quicker with less data in the chart. Be careful here though because changing aspects of the chart in different orders can produce different outputs (as an example the layout of a legend).
You fill the new FullSeriesCollection with the entire columns of A and C, specify the exact range of the data rather than the whole column.
Other changes to try, I'm not saying these will work but they are worth a shot if you haven't tried. Instead of checking for a FullSeriesCollection each time:
Do While .FullSeriesCollection.Count > 0
.FullSeriesCollection(1).Delete
Loop
The following may be quicker:
For ii = .FullSeriesCollection.Count To 1 Step -1
.FullSeriesCollection(ii).Delete
Next ii
Also, instead of .SetElement for the Chart title and Gridlines I use the following:
'You have to set the title to 'True' before it'll work with 'False'. Go figure.
.HasTitle = True
.HasTitle = False
.HasMajorGridlines = False
.HasMinorGridlines = False

Related

Animated scatter plot with plotly makes an undesired crossing of bubbles

I've done this scatter with plotly express and added an animation. Also, I adjusted the scatter to make it appears as such as a bubble chart. All works great, except for one issue. When I press the button to start the graph animation and one bubble is 'reached' and 'overtaken' by another bubble, they cross each other. By itself, it doesn't create a wrong result, but it's an undesired effect. I've showed the situation in the gif reachable with this link:
https://github.com/TheHextech/start2impact/blob/master/Data_Science/Food_Project_DataVisualization_DataManipulation/normal_animation.gif
However, if I manually drag the spinbox of the animation this effect doesn't show up (check this other link to see the gif https://github.com/TheHextech/start2impact/blob/master/Data_Science/Food_Project_DataVisualization_DataManipulation/dragged_spinbox.gif).
Why does this happen? And how can I fix this problem avoiding the 'overtake' during the normal animation? I share here the entire code of the graph:
fig = px.scatter(
data_frame=chn_food_feed,
x='production',
y='item',
size='production',
size_max=80,
animation_frame='years',
color='element',
color_discrete_map={
'Feed':'brown',
'Food':'orange'},
hover_name='item',
hover_data=dict(
item = False,
element = False),
range_x=[chn_food_feed.production.min()-5000, chn_food_feed.production.max()+50000],
range_y=[-1, 5.5])
fig.update_layout(
title="Storyline of China's top 3 Food and Feed items produced in 2013",
title_x = 0.5,
title_y = 0.95,
title_xanchor='center',
title_yanchor='top',
legend_title_text='Elements',
xaxis = dict(title='Production (1000 tons)'),
yaxis = dict(title=None))
# Speed up the animation
fig.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 250
fig.layout.updatemenus[0].buttons[0].args[1]['transition']['duration'] = 250
fig.show(renderer='notebook_connected') # For VS Code visulization of animation

How to add a gap between the axes and the plot in MATLAB

I use code like this to make a plot in MATLAB 2015:
plot(rand(1,40))
box off
ax=gca;
ax.TickDir='out';
ax.TickLength=3*ax.TickLength;
]
I want to put a bit of distance between the axes and the plot like in the figure below, which I made using Photoshop:
How can I do this?
I can think of a way to do it, but:
I don't know if it's the "right" way.
It's only good for static images (i.e. if you zoom/pan the plot, the bounds won't change accordingly).
The idea is you create two more axes and specify their positions such that they're far enough from your data, then hide the original axes (either fully or partially), which gives the desired result:
%% // Create axes and plot something:
figure();
hA(1) = axes;
hA(2) = copyobj(hA(1),gcf);
hA(3) = copyobj(hA(1),gcf);
plot(hA(1),rand(1,40));
%% // Add the new axes:
%// Move them around
FRACTION_OF_POSITION = 0.6;
hA(2).Position(1) = FRACTION_OF_POSITION*hA(2).Position(1);
hA(3).Position(2) = FRACTION_OF_POSITION*hA(3).Position(2);
%// Change their style
hA(2).Color = 'none'; hA(3).Color = 'none';
hA(2).XTick = []; hA(3).YTick = [];
hA(2).XRuler.Axle.Visible = 'off';
hA(3).YRuler.Axle.Visible = 'off';
%% // Remove the box/ticks/labels of the original axes:
if true
%// Alternative 1 (Remove everything at once, including background):
set(hA(1),'Visible','off')
else
%// Alternative 2 (Remove only certain elements):
hA(1).Box = 'off';
hA(1).XRuler.Axle.Visible = 'off';
hA(1).YRuler.Axle.Visible = 'off';
end
Which results in:
Additional considerations:
If you copyobj the axes before plotting, the axis tick values would be default - you probably don't want that. You will have to set the ticks and labels manually, OR, copyobj after plotting but then delete the line child-objects of hA(2:3).
If you want to support zoom/pan behavior, this might be acheivable using linkaxes.
Credits: the idea to use .XRuler.Axle was taken from Dan here, who in turn took it from UndocumentedMatlab.

d3 autospace overlapping tick labels

Is there a way in d3 to not draw overlapping tick labels? For example, if I have a bar chart, but the bars are only 5 pixels wide and the labels are 10 pixels wide, I end up with a cluttered mess. I'm currently working on an implementation to only draw the labels when they do not overlap. I can't find any existing way to do that, but wasn't sure if anyone else had dealt with this problem.
There is no way of doing this automatically in D3. You can set the number of ticks or the tick values explicitly (see the documentation), but you'll have to figure out the respective numbers/values yourself. Another option would be to rotate the labels such that there is less chance of them overlapping.
Alternatively, like suggested in the other answer, you could try using a force layout to place the labels. To clarify, you would use the force layout on the labels only -- this is completely independent of the type of chart. I have done this in this example, which is slightly more relevant than the one linked in the other answer.
Note that if you go with the force layout solution, you don't have to animate the position of the labels. You could simply compute the force layout until it converges and then plot the labels.
I've had a similar problem with multiple (sub-)axis, where the last tick overlaps my vertical axis in some situations (depending on the screen width), so I've just wrote a little function that compares the position of the end of the text label with the position of the next axis. This code is very specific to my use case, but could adapted easily to your needs:
var $svg = $('#svg');
// get the last tick of each of my sub-axis
$('.tick-axis').find('.tick:last-of-type').each(function() {
// get position of the end of this text field
var endOfTextField = $(this).offset().left + $(this).find('text').width();
// get the next vertical axis
var $nextAxis = $('line[data-axis="' + $(this).closest('.tick-axis').attr('data-axis') + '"]');
// there is no axis on the very right, so just use the svg width
var positionOfAxis = ($nextAxis.length > 0) ? $nextAxis.offset().left : $svg.offset().left + $svg.width();
// hide the ugly ones!
if (endOfTextField > positionOfAxis) {
$(this).attr('class', 'tick hide');
}
});
The ticks with color: aqua are the hidden ones:

D3.js: Hide the last tick on an axis?

I am using D3.js to draw an axis with ticks. I would like to hide only the last tick on the y-axis.
Maybe a picture will make it clearer. This is what my axis looks like at the moment - I'd like to hide the "21" and its associated tick.
Here is my current code:
var yAxisScale = d3.svg.axis().orient("left");
yAxisScale.scale(y_position);
yAxisScale.ticks(20).tickFormat(function(d) { return d+1; });
var yAxis = vis.selectAll("g.y.axis").data([1]);
Is there a way I can hide only the last tick, regardless of how many ticks there are on the y-axis?
I tried adding this line, but it doesn't work, even though the selectAll expression appears to return the right element.
d3.select(d3.selectAll("g.y.axis g")[0].pop()).style('opacity', 1e-6);
The opacity is still set to 1.
you should to take a look at axis.tickSize(). it allows you to set the size of the major, minor, and end ticks.
also see here for similar question:
Remove end-ticks from D3.js axis

Viewing Part of a figure

I made a simulation of 10000 times and want to view part of simulation between 5000-5200. I am able to view it with the code below, but the x-axis says 0-250. I want the x-axis to display the exact figure of 5000-5200. Also there seems to be a small gap at the end of the figure as the axis runs up to 250 for some reason. I just want to view the figure in for this set time with the x-axis showing the exact labels and without the gap at the end.
Thanks
N=10000;%Number of simulation
P=0.02;
Q = zeros(N,1); %current value of queue
X=zeros(N,1);%simulation data
Ci=0;
L=0.9;
Bu=zeros(N,1);
Bs=30;
Bd1=50;
Bd2=270;
Ti=0;
for Ti=2:N
U=rand(1);
a=log10(U);
b=log10(1-P);
c=(a/b);
d=1+c;
X(Ti)=round(d);
Ci=Ci+1;
if X(Ti)< (L)*(Bs)
Bu(Ti)=Bs;
else if X(Ti) < (L)*(Bs+Bd1)
Bu(Ti)=Bs+Bd1;
else
Bu(Ti)=Bs+Bd1+Bd2;
end
end
Ti=Ti+1;
end
plot(X(5000:5200,1),'r');
set (gca,'ylim',[0 400]);
hold on;
plot(Bu(5000:5200,1),'b');
set (gca,'ylim',[0 400]);
hold off
Plot expects two inputs, the first depicting the horizontal axis and the second depicting the vertical axis. When you do not supply two inputs, then it computes the length of the single input (in this case that length is 5200-5000 = 200), and it just uses 1 through that length (1:200 in this case) as if it is the values for the horizontal axis variable.
I think you want to issue the command:
plot(5000:5200, X(5000:5200,1), 'r')
Often Matlab will adjust plot axes for better default views, so it's probably showing the axis out to the index 250 just by virtue of some default plotting convention. You can similarly use set(gca, 'xlim', [5000 5200]) if you wish.

Resources