How can I automatically set a plots xlabel and ylabel to the variable names of x and y, when x and y are structure fields?

8 visualizzazioni (ultimi 30 giorni)
I use matlab plots (such as scatter) on a daily basis for looking at data.
It is very tedious to set the xlabel and ylabel everytime so I wrote a small function to automatically set the labels to the variable name:
function myscatter(x,y)
scatter(x,y)
xname=inputname(1);
yname=inputname(2);
xlabel(xname);
ylabel(yname);
end
Then:
foo=(1:10)
bar=(1:10)
myscatter(foo, bar)
This creates a scatter plot where the x label is already named 'foo' and the y label is already named 'bar'.
This works great when x and y are just variables stored in the workspace.
However I generally work with tables or structures of data, and the function inputname will return blank when dot indexing is used, i.e: data.foo
What I would like is to be able to create a scatter plot with data from a table or structure and still have the x and y label automatically named.
If I enter:
data.foo=(1:10)
data.bar=(1:10)
myscatter(data.foo, data.bar)
I would like it to return the scatter plot with the x and y labels as 'foo ' and 'bar'?
  2 Commenti
Image Analyst
Image Analyst il 15 Gen 2020
Why not
xlabel('foo');
ylabel('bar');
If you're going to refer to those field of data when you pass them into myscatter(), then you must already know what the field names are, so just use them.
Samuel Mousley
Samuel Mousley il 15 Gen 2020
Because my x and y labels are not always 'foo' and 'bar', they're whatever variables I want to look at in the data.
I realise I'm being a bit lazy, but I will change the variables shown in the plot many times in quick succession as I look through my data, and it's tedious to set the x and y label every single time through that method.

Accedi per commentare.

Risposta accettata

Sindar
Sindar il 16 Gen 2020
Assuming your data will always be in two fields of the same structure:
function myscatter(data,x_field,y_field, varargin )
assert(isfield(data,x_field),'Field %s not found',x_field)
assert(isfield(data,y_field),'Field %s not found',y_field)
scatter(data.(x_field),data.(y_field),varargin{:});
xlabel(x_field);
ylabel(y_field);
end
For use like this:
data.foo=(1:10)
data.bar=(1:10)
myscatter(data,'foo', 'bar')
Similar or less typing in function call and allows passing field names as variables.
Bonus: it should accept any optional arguments that scatter does
  1 Commento
Samuel Mousley
Samuel Mousley il 17 Gen 2020
Thank you, that works well and as you say, actually cuts down the amount of typing.
I can also use the same approach to make it work with tables too!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Labels and Annotations in Help Center e File Exchange

Prodotti


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by