Skip to main content

graphics - Automatizing PSfrag export



I'm in the early phase of creating a Mathematica function (or package) that exports graphics such that they can be used with $\LaTeX$'s PSfrag.


The goal


Ideally, the function should take a graphic created in Mathematica, replace all text elements with labels and export the labeled graphic along with a text file containg the corresponding \psfrag commands. It should be possible to do all the layouting in Mathematica, preserving as much of the style, font size/weight/color and positioning of the text in the graphic. The only things that should be affected are the font family (so that everything appears in $\LaTeX$ font) and the typesetting of mathematical expressions.




Problem 1: Placing text in EPS


Consider a plot that somewhere has the number 10000 as a tick (or frame tick). If you export this plot to EPS, and then import it again, the resulting Mathematica Graphics object features two text elements 10 and 000. This makes replacing single numbers with PSfrag quite a lot harder than one would think. Is there a way to force Mathematica to insert 10 000 as a single text element?




Problem 2: Extracting frame ticks


As a first try, I tried extracting all Ticks or FrameTicksfrom a graphic using AbsoluteOptions. This works nicely for many cases, but I encountered some strange behavior.


Consider the two plots



frPlot1 = Plot[x^2, {x, 0, 1000}, Frame -> True, FrameTicks -> True];
frPlot2 = Plot[x^2, {x, 0, 1000}, Frame -> True, FrameTicks -> All];

Their output looks just as one would expect from reading the documentation of FrameTicks:


True    tick marks placed automatically on bottom and left edges
All tick marks placed automatically on all edges

Determining the ticks for frPlot1 using AbsoluteOptions[frPlot1, FrameTicks] works just fine. But trying the same with frPlot2 results in an error:


Ticks::ticks: All is not a valid tick specification.


How can Allnot be a valid specification when the documentation states that it is?




Future Problems


Depending on the answers to the two questions above, there will probably arise some new questions. I will keep this post updated. I can also post the code of my first try with automatizing the tick extraction, if that is wanted.



Answer



Let me try to give you some hints.


Problem 1.


When you look at a specific tick in a Graphics it usually looks similar to the following


{200., 200., {0.00625, 0.}, {GrayLevel[0.], AbsoluteThickness[0.25]}}


it means, at position 200 draw the number 200. The next list is the specification of the tick-length and then follows a list of graphic-directives to use. I assume if you convert the label into another form, like a string, you may have more luck with your approach. Let's try something


transformTick[{pos_, label_, length_List, spec_List}] :=
{pos, ToString[label, TraditionalForm], length, spec}

p1 = Plot[x^2, {x, 0, 1000}, Frame -> True]
p2 = Show[p1, FrameTicks ->
Map[transformTick, FrameTicks /. AbsoluteOptions[p, FrameTicks], {2}]]

Mathematica graphics Mathematica graphics


It seems the Ticks are a bit smaller and the dot after the number does not appear in the original but otherwise it looks OK for me. If you now compare



ImportString[ExportString[#, "EPS"], "EPS"] & /@ {p1, p2}

it seems (at least on my machine) that the numbers are tight together in the second case. Even if this simple idea does not work, you now know how you can transform the Ticks into another form.


Problem 2.


Maybe I can help you with a workaround. It seems to me that when you use All as value to FrameTicks you just get the same ticks on the other side. Other differences are really small.


p1 = Plot[x^2, {x, 0, 1000}, Frame -> True]
p2 = Plot[x^2, {x, 0, 1000}, Frame -> True, FrameTicks -> All]

Mathematica graphics Mathematica graphics


Now you say, you need to extract the Ticks for the All setting but I don't understand why. Let's look again on my first code-block with the tick. Note, that it does not contain a position! It does only contain an x-value where the tick is, the y-value is calculated automatically. Therefore, the tick-specification for the same tick on the top does look exactly the same.



Well, if this were true, than the only thing necessary to clone FrameTicks->All is to use the default setting and copy ticks for the first axis to the third and the ticks for the second axis to the fourth axis? Right!


Show[p1, FrameTicks -> (#[[{1, 2, 1, 2}]] &[FrameTicks /. AbsoluteOptions[p]])]

Mathematica graphics


And it's getting even better: If you study the help-page of FrameTicks carefully, you find this example


Plot[Cos[x], {x, 0, 10}, Frame -> True, 
FrameTicks -> {{0, {Pi, Pi, {.4, 0}, Directive[Blue, Thick]}, 2 Pi,
3 Pi}, None}, FrameStyle -> Directive[Gray, Dashed],
FrameTicksStyle -> Directive[Orange, 12]]


Mathematica graphics


which suggests, that for setting ticks on top and bottom equally, you just have to supply only 1 list. This can be generalized to when you give 2 lists and not {} explicitly for the 3rd and 4th list, you get ticks everywhere.


Et voila:


Show[p1, FrameTicks -> Take[FrameTicks /. AbsoluteOptions[p], 2]]

works as expected.


Conclusion here is, that you have all information about the ticks even if you don't use FrameTicks->All. If I'm right, and you needed the ticks only to adjust the label, than you can check the setting of FrameTicks with Options[gr,FrameTicks] and if it is set to All, you can build your own version with


Show[gr, FrameTicks -> Automatic]

and extracting and transforming the ticks of this.




Since we cleared in chat that the overall goal is to replace FrameTicks in an EPS graphics with the appropriate or custom LaTeX code I want to give an implementation which might be of use. The approach will work as follows:



  • I extract the FrameTicks from a given Mathematica Graphics.

  • I will create a labels for each tick which will be a string-replacements that appears in the eps file and can be found easily by PSFrag.

  • Therefore, the label must be unique and

  • should have about the same width as the original tick


Labels will consist of a unique id and, if necessary a padding with "x" to make it as large as the original tick. The calculation of the width will work as follows: (1) we estimate the width of an "x" and (2) create a Rasterized version of the tick to give its ImageDimensions in means of x-widths.


xwidth[] := xwidth[] = First[ImageDimensions[

Rasterize@StringJoin@ConstantArray["x", 10]]]/10.;

SetAttributes[expressionWidth, {HoldFirst}];
expressionWidth[expr_] := With[ {
x = xwidth[],
exprwidth = First[ImageDimensions[Rasterize[HoldForm[expr]]]]},
Round[exprwidth/x]
]

Creating a new label is then (1) asking a global counter for a new id and create the label-string which is about the same width as the original tick. Minimum tick-width is 2 here



$label = 10;
getLabel[] := $label++;
SetAttributes[createLabel, {HoldFirst}];
createLabel[tick_] :=
Module[{size = Max[2, expressionWidth[tick]], label},
label = Which[size > 2,
StringJoin[ConstantArray["x", size - 2]] <>
IntegerString[getLabel[]],
True,
IntegerString[getLabel[]]

]
]

The transformation of the Graphics itself is simple. I use a transformTick function which creates a new encoded tick and Sows the LaTeX code for PSFrag. In createPSFragGraphics I replace every FrameTick with the encoded ones and collect the LaTeX-snips with Reap


SetAttributes[transformTick, {HoldFirst}];
transformTick[t : {_, "", _List, _List}] := t;
transformTick[{pos_, tick_, length_List, spec_List}] :=

With[{label = createLabel[tick]},
Sow["\\psfrag{" <> label <> "}{$" <>

ToString[TeXForm[ToString[tick, TraditionalForm]]] <> "$}"];
{pos, label, length, spec}
]

createPSFragGraphics[gr_] := Reap[Show[#, FrameTicks ->
Map[transformTick, FrameTicks /. AbsoluteOptions[#, FrameTicks], {2}]] &@gr];

Final note, since you may have seen all the HoldFirst attributes. I want to prevent ticks like those


Mathematica graphics


from evaluation into 3000000. It would give a wrong width otherwise.



Testing the label-encoding


gr = Plot[x^2, {x, 0, 1000}, Frame -> True];
{grenc, labels} =
createPSFragGraphics[Plot[x^2, {x, 0, 1000}, Frame -> True]];
grenc
Column[Flatten[labels]]

In grenc you find the encoded Graphics you want to export to EPS. In comparison with the original one, you see that label-lengths almost match with the tick-width


Mathematica graphics


Furthermore, you get the LaTeX code required for PSFrag in labels



\psfrag{10}{$0.$}
\psfrag{xx11}{$200.$}
\psfrag{xx12}{$400.$}
\psfrag{xx13}{$600.$}
\psfrag{xx14}{$800.$}
\psfrag{xxx15}{$1000.$}
\psfrag{16}{$0.$}
\psfrag{xxxxx17}{$200000.$}
\psfrag{xxxxx18}{$400000.$}
\psfrag{xxxxx19}{$600000.$}

\psfrag{xxxxx20}{$800000.$}
\psfrag{xxxx21}{$1.\times 10^6$}


I had to learn the hard way that Linux seems to export every string or number as a separate letter in an EPS file. This makes is completely unusable for PSFrag since this relies on the fact that the labels in EPS files are given as single show command. If you never looked at postscript-code, then the documentation to PSFrac explains this quite nice.


Comments

Popular posts from this blog

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1.