I am trying to write a function that read what is the FrameLabel of a plot and translates that to filesystem friendly name, that, for instance does not contain "/" or greek characters and so on ...

The goal is to get a function that exports a plot to PDF and automatically gives it a meaningful file name of the type XAxisLabel_YAxisLabel_PlotLabel.pdf

Here is what I got so far.

1) a translation for unwanted character and strings:

  FileSystemFriendly={\left->,\right->,\text{->,$->,\{->,\}->, ->,\->,{->,}->,/->.over.,>->.gt.,<->.lt.,=->.eq.}

2) a function that actually takes the plot and looks for the labels

      res=Export[StringReplace[ToString[TeXForm[FrameLabel/. inputplot[[2]]]],FileSystemFriendly]<>__<>StringReplace[ToString[TeXForm[PlotLabel/. inputplot[[2]]]],FileSystemFriendly]<>.pdf,inputplot];
      Print[File put in,respath=Directory[]<>/<>res];
      Button[Open it!,SystemOpen[respath]]

This is giving some acceptable results so far, which means that the filenames are usable on a regular filesystem. However the typical name is plenty of garbage, for instance for a very simple label I still get (beginarraycc1-Cumulative&Nonep_T,j_ 3&Noneendarray)__PlotLabel which has lots of stuff that I do not know where it comes from. I could chase and remove one by one the unwanted stuff but I feel like I am not doing it the right way. Hence I wanted to ask for some advice.

Thanks for sharing your knowledge, Roberto

  • $\begingroup$ You should post code for some of the offending plots as well to make reproduction of the problem possible. $\endgroup$
    – Yves Klett
    Aug 1 '14 at 5:05
plt1 = Plot[x^2, {x, 0, 2},
  PlotLabel -> "Function Plot",
  AxesLabel -> {x, f[x]}]

enter image description here

plt2 = Plot[x^2, {x, 0, 2},
  PlotLabel -> "Function Plot",
  Frame -> True, Axes -> False,
  FrameLabel -> {x, f[x]}]

enter image description here

Here is a skeleton for the file name

fileName[plt_] :=
      ToString /@ (({
             Reverse[FrameLabel], AxesLabel, PlotLabel} /.
            AbsoluteOptions[plt]) /.
          None -> Sequence[] //
    " " -> ""] <> ".pdf" //






This is similar to Bob's answer, but this is how I would write it:

plt2 = Plot[x^2, {x, 0, 2}, PlotLabel -> "Function Plot", Frame -> True, Axes -> False, FrameLabel -> {x, f[x]}]

fileName[{plabel_, {{ylabel_, _}, {xlabel_, _}}}] := Module[{clean},
  clean = StringReplace[ToString@#, Except[LetterCharacter] -> ""] & /@ {plabel, ylabel, xlabel};
  StringJoin[Riffle[clean, "_"], ".pdf"]

fileName[{PlotLabel, FrameLabel} /. Options[plt2]]
(* Out: "FunctionPlot_fx_x.pdf" *)

You can change Except[LetterCharacter] -> "" to something else or add allowed characters to that list. Currently it will remove any characters that aren't letters.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.