13

How can I align tick labels so the tick label text ends centered under the data point? Of Course it works fine with a rotation of 90 Degrees, but not with 45 or similar angles.

I see an example of how to do this charts but not with Plot or ListPlot https://mathematica.stackexchange.com/a/2656/388

d = Table[n, {n, 10}];
xticks = Table[{n, 
Rotate["The y value is " <> ToString[n], 45 Degree]}, {n, d}];
ListPlot[d, Frame -> True, 
 FrameTicks -> {{Automatic, None}, {xticks, None}}]

Labeled list plot

Davorak
  • 407
  • 4
  • 7

2 Answers2

14

Similar to Szabolcs's and my answers here, I would suggest writing your own custom tick function, so that the labels are set into a Pane which can be both Rotated and have ImageMargins.

myTickList[min_, max_, seg_, shift_?NumericQ, phi_?NumericQ, len_: 0.01] := 
 Table[{i, Rotate[Pane[Style["y =" <> ToString[i], LineSpacing -> {0, 12}], 
     FrameMargins -> {{shift, 0}, {0, 0}}], phi], {len, 0}}, 
    {i, If[Head[seg] === List, Union[{min, max}, seg], 
    Range[min, max, seg]]}]

Examples:

fakedata = Accumulate@RandomVariate[NormalDistribution[0, 0.5], 40];

ListLinePlot[fakedata, Frame -> True, GridLines -> {None, Automatic}, 
 FrameTicks -> {{Automatic,  Automatic}, {myTickList[0, 40, 4, 25, Pi/4], None}}]

enter image description here

ListLinePlot[fakedata, Frame -> True, GridLines -> {None, Automatic}, 
 FrameTicks -> {{Automatic, Automatic}, {myTickList[0, 40, 4, 5, Pi/3], None}}]

enter image description here

Verbeia
  • 34,233
  • 9
  • 109
  • 224
11

Brett Champion posted a nice clean method in Labeling a bar chart, changing how rotated labels are centered that can be applied here as well:

center = Row[{#, Invisible[#]}, "\[NegativeThickSpace]"] &;

d = Range[10];

xticks = Table[{n, center @ Rotate["The y value is " <> ToString[n], 45 Degree]}, {n, d}];

ListPlot[d, Frame -> True, FrameTicks -> {{Automatic, None}, {xticks, None}}]

enter image description here

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 1
    I like this solution, but the placement still looked a bit off. This is easy to adjust by adding additional characters of [NegativeThickSpace] to the Row command. However, since Mathematica automatically subs out the name for a blank character that's difficult to edit, I found it easier to instead use FromCharacterCode[Table[62340, {x}]] and play with the value of x until it looks good. x=4 was the magic number for me. – clr66 May 01 '19 at 23:51