3

The grid formed below aligns its columns as I want on the decimal point:

x = 2. Pi/24 Range[0, 5];
data = Transpose[{x, Chop@Sin[x]}];

Grid[data, Alignment -> {"."}]

Grid with columns aligned on decimal point

Now I want to prepend a row to the grid with its two items centered. I tried the following, which if I understand the documentation, ought to do it:

Grid[Prepend[data, {"x", "sin x"}], Alignment -> {Center, {"."}}]

Grid with header row, original rows misaligned

But that just centers all entries in each column.

How do I get just the first row's entries to be centered but the remaining rows to be aligned on the decimal point?

murray
  • 11,888
  • 2
  • 26
  • 50

2 Answers2

4

This should do it. In Alignment docs under Generalizations & Extensions.

Grid[Prepend[data, {"x", "sin x"}],
 Alignment -> {".", Automatic, {{1, 1} -> Center, {1, 2} -> Center}}]

There is an odd ItemSize issue in the first column though, stemming from the "." alignment algorithm as I recall. E.g.

x = 2. Pi/24 Range[0, 5];
data = Transpose[{x, Chop@Sin[x], Chop@Cos[x]}];

Grid[Prepend[data, {"x", "sin x", "cos x"}], Alignment -> {".", Automatic, {{1, 1} -> Center, {1, 2} -> Center, {1, 3} -> Center}}, Frame -> All]

enter image description here

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
  • Does what I want, although ugly with the several table coordinate pairs required! Is there a way that uses the "recycling" of alignment specs? – murray Sep 05 '21 at 16:44
  • I had a look at that but couldn't get it working. I use coordinate pairs for cell background colours and usually have a some kind of map function to build the coordinate expression. – Chris Degnen Sep 05 '21 at 17:37
  • Cycling works for columns, e.g. Grid[ReplacePart[Array["x"&, {10,6}], {#,#}->"---------" &/@Range[6]], Alignment->{{Center, {Right, Left}, Center}}, Frame->All] – Chris Degnen Sep 06 '21 at 14:08
  • Yes the example is in Generalizations & Extensions for Alignment. But why is the "Automatic" necessary? – crabtree Feb 12 '24 at 19:31
3

The following, using Item as suggested in https://mathematica.stackexchange.com/a/180225/148, does what I want, although I'd still prefer a simpler way using the spec recycling aspect of Alignment to avoid Item.

hdr = Item[Text[#], Alignment -> Center] & /@ {"x", "sin x"}; Grid[
 Prepend[data, hdr], Alignment -> "."]

Properly aligned grid

murray
  • 11,888
  • 2
  • 26
  • 50