3
$\begingroup$

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?

$\endgroup$
4
$\begingroup$

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

$\endgroup$
3
  • $\begingroup$ Does what I want, although ugly with the several table coordinate pairs required! Is there a way that uses the "recycling" of alignment specs? $\endgroup$
    – murray
    Sep 5 at 16:44
  • $\begingroup$ 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. $\endgroup$ Sep 5 at 17:37
  • $\begingroup$ Cycling works for columns, e.g. Grid[ReplacePart[Array["x"&, {10,6}], {#,#}->"---------" &/@Range[6]], Alignment->{{Center, {Right, Left}, Center}}, Frame->All] $\endgroup$ Sep 6 at 14:08
3
$\begingroup$

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

$\endgroup$

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.