Message Boards Message Boards


PlotLabel with the use of variables

Posted 7 years ago
7 Replies
3 Total Likes


given that I defined 2 variables


I would like to have a Plot with the Label saying

"solution with 10 x 20 grid points" .

What I tried so far is using Text[ ], e.g. PlotLabel -> Text[n "grid points"] produce the caption

"10 grid points" .

However, PlotLabel -> Text[ n x m "grid points"] produces the caption

"200 grid points" ,

which is not what I am aiming for.

Moreover, Mathematica always places the numbers in front of the text, e.g. PlotLabel -> Text["solution with" n "grid points"] results in the caption

"10 solution with grid points" ,

which is again not what I want.

Does anyone know how to do this properly?

7 Replies
Posted 7 years ago

The new StringTemplate in V10 is a nice way to do this. Here a string is constructed for use as a plot label. The code could also be used directly as the option value in the plot function.

In[2]:= n = 10; m = 20;

In[3]:= label = 
 StringTemplate["solution with `1` x `2` grid points"][n, m]

Out[3]= "solution with 10 x 20 grid points"

David's solution is more elegant, but you can also use StringJoin (or the shortcut <>) for compatibility with older versions:

n = 10; m = 20;
label = "solution with " <> ToString@n <> " x " <> ToString@m <>  " grid points"

You can also wrap that in Style to format the label.

n = 10; m = 20;
label = Style["solution with " <> ToString@n <> " x " <> ToString@m <> " grid points", Bold, 12, Black]
Posted 7 years ago

Tim is quite right -- for versions earlier than 10 StringTemplate is not available, but this is works fine.

Posted 7 years ago

Thank you both very much!

I'm using V but having different, and strange results: using StringTemplate doesn't work, but

does. What am I not understanding?

Posted 10 days ago

In the first case, you are using StringTemplate incorrectly. StringTemplate["string"] produces a TemplateObject which needs to be applied to arguments. Since all you want is the string as written, that is not useful here.

Note in my example above, the StringTemplate is applied to the argruments [n,m].

Okay, thanks for the clarification.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract