Square root symbol label in Matlab - matlab

How to get the square root sign inside a legend?
I tried \surd, but did not consider all my expression below this symbol.
\sqrt and \square do not work at all.
m=[2 4.8 7 9.1 11.5 15 20 29 59 90 130 190 250];
size(Te);
s=0:0.02:0.246;
size(s);
E0=0.1;
t0=0.05;
f=0.01;
I0=2e9;
I1=1e14.*[m./(3680.*(1.08)^(1./3))].^(1.5);
hold on
Ifitting=I0./(sqrt(2.*pi).*f).*exp(-[s-t0].^2./(2.*f.^2));
[ay,h1,h2]=plotyy(s.*1e6,I1,s.*1e6,Ifitting,'loglog','plot')
axes(ay(1)); ylabel(' Intensity');
axes(ay(2)); ylabel('Intensity [fitting]');
set(ay(1),'Ylim',[0 2e12])
set(ay(2),'Ylim',[0 2e12])
xlabel('time [\mu m]','FontSize',16,'FontName','Times-Roman');
set([h1],'marker','o')
set([h2],'marker','o')
b=legend([h1 h2], ['I=10^{14}'],['I_{fitting}=I_0$$\sqrt{(2)\sigma}$$e^{\sigma}']);
set(b,'Interpreter','latex','fontsize',24)

you can try this:
plot(sqrt(1:10));
h = legend(['$$\sqrt{blah}$$'])
set(h,'Interpreter','latex','fontsize',24)

Create the legend with LaTeX-style text, and then set to 'latex' the 'interpreter' property of all children of the lenged that are of type 'text':
leg = legend('$\sqrt{x-1}$'); %// this will give a warning; ignore it
t = findobj('Parent',leg,'Type','text');
set(t,'Interpreter','latex')
It would be easier if legend accepted the 'interpreter' property directly (legend('$\sqrt{x-1}$','interpreter','latex')), but it doesn't, at least in R2010b. ... However, it seems to work if after the legend object has been created; see natan's answer.

Related

Matlab: GUI radio button SelectionChangedFn Callback

I'm trying to figure out how to make a GUI with radio buttons that will enable/disable options based on radio button selections. Here's an example of one way I have tried:
fig = uifigure('NumberTitle','off','Name','Option Selection','Position',[750,300,460,520]);
panel1 = uipanel(fig,'Title','Options','Position',[140,80,200,280]);
bg = uibuttongroup(fig,'Position',[140 290 200 51],'SelectionChangedFcn',#bselection);
rb1 = uiradiobutton(bg,'Position',[5 30 100 20],'FontWeight','bold');rb1.Text = 'Option 1';
rb2 = uiradiobutton(bg,'Position',[5 10 100 20],'FontWeight','bold');rb2.Text = 'Option 2';
Opt1_label = uilabel(panel1,'text','Option 1','Position',[5 180 100 20],'FontWeight','bold');
Opt1_field = uieditfield(panel1,'text','Position',[5 160 100 20]);
Opt2_label = uilabel(panel1,'text','Option 2','Position',[5 60 250 20],'FontWeight','bold');
Opt2_field = uitextarea(panel1,'Position',[5 15 190 45]);
function bselection(bg,Opt1_label,Opt1_field,Opt2_label,Opt2_field)
if bg.Buttons(1).Value == 1
Opt1_label.Enable=1;
Opt1_field.Enable=1;
Opt2_label.Enable=0;
Opt2_field.Enable=0;
elseif bg.Buttons(2).Value == 1
Opt1_label.Enable=0;
Opt1_field.Enable=0;
Opt2_label.Enable=1;
Opt2_field.Enable=1;
end
end
The enable/disable if statement works standalone, but I cannot figure out how to get it to work as a callback. Option 2 is not disabled even though option 1 is selected first by default, and if I select another radio button, either nothing changes or I will get an error saying the Enable handle isn't found.
Any ideas are much appreciated
Thanks in advance!
You have configured your function bgselection() to be a callback function for a UI element. Callback functions have two specific rules for the input arguments:
The first argument must be the handle of the object that called the function, and the second must be "eventData" for the callback event. So in your function, the argument Opt1_label is being treated as a eventData variable. Since it does not have the information expected in that variable, there is an error. So to follow this rule, change your function definition to:
function bselection(bg,eventData,Opt1_label,Opt1_field,Opt2_label,Opt2_field)
The second rule is that if you want to have more than the required two input arguments, you need to list them in a cell array when the function is assigned to the object. So in your case, define the uibuttongroup like this:
bg = uibuttongroup(fig,'Position',[140 290 200 51],'SelectionChangedFcn',{#bselection,Opt1_label,Opt1_field,Opt2_label,Opt2_field});
You will have to move the definitions of Opt1_, Opt2_ etc before the bg statement, so that they exist and can be included in the cell array.
You can see the documentation for this here. There are a couple other options for passing arguments, but these are the most common methods.
Also, the eventData has some useful information, such as the label of the button that is selected. Try adding disp(eventData) to the function to see what is included there.

Circular layout with edge bundling and labels in graph-tool

I am very new to graph visualizations and software like graph-tool (gt). My main field is mathematics, but I am somewhat familiar with Python and programming in general. However, I'm not a programmer, so my code may be less than elegant; any suggestions of improvement will be gratefully appreciated.
Description:
I am very fond of the circular layout with edge bundling used to visualize very large graphs. As an example, I am trying to plot the C.Elegans connectome using the wonderful Python module graph-tool by Tiago Peixoto. For this I use the following:
import graph_tool.all as gt
g_celegans = gt.load_graph("c.elegans_neural.male_1.graphml")
v_prop = g_celegans.vertex_properties
celegans_state = gt.minimize_nested_blockmodel_dl(g_celegans)
celegans_state.draw(vertex_text = v_prop['name'], bg_color = 'w')
which produces:
Questions:
How could I (in gt) place the vertex labels on a line drawn from the center? Like this
Can I plot a similar layout, i.e. circular and edge bundling, but using a clustering (partition of the vertices) of my own, instead of the stochastic block model? In a sense, I guess I would just like to be able to use the circular + edge bundling feature on its own. Or am I missing the whole point somewhat?
(Would anyone recommend a good introductory treatment on graph visualizations including this type (connectogram)?)
Attempt at Question 1:
So, I managed to at least get somewhere with this:
def getAngle(vec):
norm_vec = vec / np.linalg.norm(vec)
one_vec = np.array([1,0])
dot_product = np.dot(norm_vec, one_vec)
return np.arccos(dot_product)
text_rot = [0]*len(list(text_pos))
for i, p in enumerate(text_pos):
if p[0]>=0 and p[1]>=0:
text_rot[i] = getAngle(p)
elif p[0]>=0 and p[1]<0:
text_rot[i] = -getAngle(p)
elif p[0]<0 and p[1]>=0:
text_rot[i] = getAngle(p)-np.pi
elif p[0]<0 and p[1]<0:
text_rot[i] = -getAngle(p)+np.pi
text_rot = np.asarray(text_rot)
t_rot = g_celegans.new_property('v','float', vals = text_rot)
options = {'pos': pos,
'vertex_text': v_prop['name'],
'vertex_text_rotation':t_rot,
'bg_color': 'w',
'vertex_shape': 'none',
'vertex_font_size': 5,
'edge_end_marker': 'none'
}
celegans_state.draw(**options)
which produces:
So, the rotation is fine, but I would like to offset the labels a bit further out. Now they're in the center of an invisible vertex. There are two vertex properties called 'text_position' and 'text_offset', which you may read about here.
Now, any value for 'vertex_text_position', such as -1 or 'centered' or if I pass a VertexPropertyMap object like for 'vertex_text_rotation' above, generates an IndexError:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-197-d529fcf5647e> in <module>
9 }
10
---> 11 celegans_state.draw(**options)
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/inference/nested_blockmodel.py in draw(self, **kwargs)
986 draws the hierarchical state."""
987 import graph_tool.draw
--> 988 return graph_tool.draw.draw_hierarchy(self, **kwargs)
989
990
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in draw_hierarchy(state, pos, layout, beta, node_weight, vprops, eprops, hvprops, heprops, subsample_edges, rel_order, deg_size, vsize_scale, hsize_scale, hshortcuts, hide, bip_aspect, empty_branches, **kwargs)
2121 kwargs[k] = u.own_property(v.copy())
2122
-> 2123 pos = graph_draw(u, pos, vprops=t_vprops, eprops=t_eprops, vorder=tvorder,
2124 **kwargs)
2125
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in graph_draw(g, pos, vprops, eprops, vorder, eorder, nodesfirst, output_size, fit_view, fit_view_ink, adjust_aspect, ink_scale, inline, inline_scale, mplfig, output, fmt, bg_color, **kwargs)
1074 vprops.get("fill_color", _vdefaults["fill_color"]),
1075 vcmap)
-> 1076 vprops["text_color"] = auto_colors(g, bg,
1077 vprops.get("text_position",
1078 _vdefaults["text_position"]),
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in auto_colors(g, bg, pos, back)
724 return color_contrast(back)
725 c = g.new_vertex_property("vector<double>")
--> 726 map_property_values(bgc_pos, c, conv)
727 return c
728
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/__init__.py in map_property_values(src_prop, tgt_prop, map_func)
1189 u = GraphView(g, directed=True, reversed=g.is_reversed(),
1190 skip_properties=True)
-> 1191 libcore.property_map_values(u._Graph__graph,
1192 _prop(k, g, src_prop),
1193 _prop(k, g, tgt_prop),
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in conv(x)
722 return color_contrast(bgc)
723 else:
--> 724 return color_contrast(back)
725 c = g.new_vertex_property("vector<double>")
726 map_property_values(bgc_pos, c, conv)
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in color_contrast(color)
694 def color_contrast(color):
695 c = np.asarray(color)
--> 696 y = c[0] * .299 + c[1] * .587 + c[2] * .114
697 if y < .5:
698 c[:3] = 1
IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed
If I do 'vertex_text_offset = pos', this would mean that I offset each vertex by its own coordinates, and I could then just scale by say 0.1 to get them appropriately far out, which actually DID work great without rotation. Then I rotated the text, which yielded this (without scaling):
The problem seems to be that the center for rotation is the center of the vertex, which is not ideal if the text is moved out from the vertex. So, even if 'vertex_text_position' above would have worked, I'm guessing the rotation would have messed that up as well.
Weirdly enough, If I rotate the vertices using 'vertex_rotation' instead, the labels are rotated along with them (great!), but when I offset the text with vertex position (which should "push" outwards), I get the same faulty plot as above.
Next I tried 'vertex_shape = circle', and filling the vertices with white using 'vertex_fill_color = 'w''. Thus I would push the text out a bit from the edge by increasing the size of the vertex. For some reason this made all the edges of the graph white as well; so no colors at all in the plot. I guess the edges are thus colored based on the vertex colors.
What I ended up doing is to use the vertex properties 'text_out_color' and 'text_out_width', with a width of 0.003. This gives a nice bold style to the text, which makes it more readable against the colored background.
But, now I'm pretty much out of ideas.
Do anyone know a solution to my problem? i.e. placing the labels like I have them, but moving them further out (in the direction outwards from the center) or framing them in white so that they're more readable, but so that the plot still looks nice; as well as to question 2 above.
This is a couple months late so hopefully you figured it out but I'll leave this here for future reference:
To get those labels to look the way you want them to in this case is when you call the draw function you'll want to specify the position of the vertex text like so:
celegans_state.draw(vertex_text = v_prop['name'], bg_color = 'w', vertex_text_position='centered')
(as can be seen in the list of properties in the documentation 'centered' gives this exact effect: https://graph-tool.skewed.de/static/doc/draw.html#graph_tool.draw.graph_draw)
To get a circular graph I figure you want to use the radial tree layout (https://graph-tool.skewed.de/static/doc/draw.html?highlight=radial_tree_layout#graph_tool.draw.radial_tree_layout)
Hopefully this helps!

Gantt Chart in Matlab

Do you know how to plot a Gantt chart in Matlab without using a third-party software?
At the end I would love to obtain something like this:
What I was able to obtain so far is
using this code:
% Create data for childhood disease cases
measles = [38556 24472 14556 18060 19549 8122 28541 7880 3283 4135 7953 1884]';
mumps = [20178 23536 34561 37395 36072 32237 18597 9408 6005 6268 8963 13882]';
chickenPox = [37140 32169 37533 39103 33244 23269 16737 5411 3435 6052 12825 23332]';
% Create a stacked bar chart using the bar function
fig = figure;
bar(1:12, [measles mumps chickenPox], 0.5, 'stack');
axis([0 13 0 100000]);
title('Childhood diseases by month');
xlabel('Month');
ylabel('Cases (in thousands)');
legend('Measles', 'Mumps', 'Chicken pox');
That is not what I want but, maybe, goes in this direction
Here, I share the solution I have just found (maybe it is not the most elegant one but it works for the purpose I have):
[the main idea is to draw a bar and "delete" the beginning overdrawing up on it another white bar]
Let's say you have two vector:
start =[6907402; 2282194; 4579536; 2300332; 10540; 2307970; 4603492; 0];
stop =[9178344; 9168694;6895050; 4571400; 2280886; 4579044; 6897152 ;2271186];
There are 8 elements in each: every element is a task. In the start array, there is the start time of each task and in stop there is the end of the "execution" of a given task.
barh(stop)
hold on
barh(start,'w')
At the end here you have the Gantt:
UPDATE:
My scripts are evolved of course and, more, on the matlab website, there is more information. Here 2 example more to complete the answer:
Option 1:
Positions=[1,2,3,4];
Gap_Duration=[0,2,5,3,5,3;
3,5,3,5,3,4;
9,3,0,0,12,2;
13,2,2,2,8,3];
barh(Positions,Gap_Duration,'stacked');
Option 2:
Positions=[1,2,3,4];
Gap_Duration=[0,2,5,3,5,3;
3,5,3,5,3,4;
9,3,0,0,12,2;
13,2,2,2,8,3];
barh(Positions,Gap_Duration,'stacked');
set(H([1 3 5]),'Visible','off')

bar chart display all cateogries

I have a bar chart. It has 25 bars all representing a different category. The chart is fine however it only prints out a few of the categories.
I thought by using the line below that it would display all 25 categories that I have specified in x_labels.
set(gca,'XtickL',x_labels);
I also use the method rotateXLabel and rotate the labels 90 degrees so they are not over writing each other. However still only display some of the categories. How can I display all of them?
update
Here is my data,
'Health Care' 4.72629799981083
'Capital Goods' 4.09458147368759
'Transp' 3.98149295925542
'Media' 1.79439005788530
'Insurance' 1.69956150439052
'Commer Serv' 1.39773924375053
'Food & Staples' 1.37870312358688
'Tech Hardw' 1.14006008338028
'Div Finan' 1.07437424540054
'Retailing' 0.799227696500581
'Cons Durab' 0.484704646767555
'Semiconduct' -0.0668927175281457
'Cons Serv' -0.0994263844790881
'Software' -1.13770277184728
'Auto&Comp' -1.14193637823934
'Materials' -1.52052729345776
'Real Estate' -1.58166267932780
'HH & Prod' -1.68076878183555
'Food Bever' -1.73283367572542
'Pharma' -1.90119783888618
'Telecom' -2.04480219189470
'Utilities' -2.20510498991084
'Energy' -2.36405808621777
'Banks' -5.09421924506606
another update
Found the solution here. Its not quite 100% perfect though as some of my labels are too long so the chart cuts them off. Need to work out how to get round that issue
[pp,h1,h2]=plotyy((1:length(risk_tot)),risk_tot,(1:length(risk_tot)),risk_cont,'bar','stem');
xData = get(h1,'XData');
set(gca,'Xtick',linspace(xData(1),xData(end),length(x_labels(:, 1))));
Is this what you are looking for?:
value is vector with the provided values
label is a cell with the provided strings
bar(value);
set(gca, 'XTick', 1:length(value))
set(gca, 'XTickLabel', label)
grid on
rotateXLabels(gca(), 90)

Is there a limit to the amount of data you can put in a MATLAB pie/pie3 chart?

I have everything going swimmingly on my pie chart and 3D pie charts within MATLAB for a dataset, however, I noticed that even though I have 21 pieces of data for this pie-chart being fed into the pie-chart call, only 17 appear.
PieChartNums = [ Facebook_count, Google_count, YouTube_count, ThePirateBay_count, StackOverflow_count, SourceForge_count, PythonOrg_count, Reddit_count, KUmail_count, Imgur_count, WOWhead_count, BattleNet_count, Gmail_count, Wired_count, Amazon_count, Twitter_count, IMDB_count, SoundCloud_count, LinkedIn_count, APOD_count, PhysOrg_count];
labels = {'Facebook','Google','YouTube','ThePirateBay','StackOverflow', 'SourceForge', 'Python.org', 'Reddit', 'KU-Email', 'Imgur', 'WOWhead', 'BattleNet', 'Gmail', 'Wired', 'Amazon', 'Twitter', 'IMDB', 'SoundCloud', 'LinkedIn', 'APOD', 'PhysOrg'};
pie3(PieChartNums)
legend(labels,'Location','eastoutside','Orientation','vertical')
This goes for the labels and the physical graph itself.
Excuse the poor formatting in terms of the percentage cluster, this is just a rough version. I tried every orientation and even splitting labels between the orientations without any luck.
Quasi-better resolution for Pie Chart -- Imgur Link
Like Daniel said - it appears that there simply isn't any non-negative data for the missing slices. I tried reproducing your problem with the following initialization, yet it resulted in normal-looking chart:
[ Facebook_count, Google_count, YouTube_count, ThePirateBay_count, ...
StackOverflow_count, SourceForge_count, PythonOrg_count, Reddit_count, ...
KUmail_count, Imgur_count, WOWhead_count, BattleNet_count, Gmail_count, ...
Wired_count, Amazon_count, Twitter_count, IMDB_count, SoundCloud_count, ...
LinkedIn_count, APOD_count, PhysOrg_count] = deal(0.04);
In order to verify this hypothesis - could you provide the data you're using for the chart? Do you get any warnings when plotting the chart?
From inside the code of pie.m:
if any(nonpositive)
warning(message('MATLAB:pie:NonPositiveData'));
x(nonpositive) = [];
end
and:
for i=1:length(x)
if x(i)<.01,
txtlabels{i} = '< 1%';
else
txtlabels{i} = sprintf('%d%%',round(x(i)*100));
end
end
You can see that MATLAB doesn't delete valid slices, but only renames them if the data values are small.