贝利撒留给出了基本的方法。我将介绍一种高级方法,因为您似乎很想学习。
首先让我说,我看到了我认为是对您的代码的简化,并且我做了它们,希望没有错误。
我将在下面的插图中使用此示例数据:
data = Prepend[
RandomInteger[99, {5, 12}],
DateString[{1, #}, "MonthName"] & /@ Range@12
];
目标
-
由于使用的主要函数是Grid,因此允许将选项传递给它是有意义的。
-
您有一系列选项来定义您的表格。我希望能够方便地更改这些。
-
我希望Grid 不理解的自定义选项的可能性。
实施
目标 #1
添加了一个参数模式opts:OptionsPattern[],它匹配任何Option -> Setting 参数序列,并将其命名为opts。 (有关更多信息,请参阅:OptionsPattern。)然后,opts 被插入到 Grid 的其他选项之前的基本函数中。这允许任何显式给定的选项覆盖默认值,或者给出新的选项。
customTabular[data_, opts : OptionsPattern[]] :=
Grid[MapAt[Rotate[#, 90 Degree] & /@ # &, data, 1],
opts,
Background -> {{{White, Pink}}},
Dividers -> {All, {2 -> True}},
ItemSize -> {1 -> 5},
Alignment -> {Center, {1 -> Top}},
Frame -> True,
FrameStyle -> Thickness[2],
ItemStyle -> Directive[FontSize -> 15, Black, Bold]
] // Text
例子:
customTabular[data]
customTabular[data, Background -> LightBlue]
目标 #2
定义表格格式的选项可以与函数体分开。这将允许它们方便地更改或引用。我首先用ClearAll 清除之前的定义。然后我为customTabular设置默认Options:
ClearAll[customTabular]
Options[customTabular] =
{Background -> {{{White, Pink}}},
Dividers -> {All, {2 -> True}},
ItemSize -> {1 -> 5},
Alignment -> {Center, {1 -> Top}},
Frame -> True,
FrameStyle -> Thickness[2],
ItemStyle -> Directive[FontSize -> 15, Black, Bold]};
现在功能正常。这里Options@customTabular 得到了上面给出的规则。
customTabular[data_, opts : OptionsPattern[]] :=
Grid[MapAt[Rotate[#, 90 Degree] & /@ # &, data, 1],
opts,
Sequence @@ Options@customTabular
] // Text
现在您可以使用SetOptions 轻松更改默认设置。示例:
SetOptions[customTabular,
Background -> {{{LightMagenta, LightOrange}}}
];
customTabular[data]
目标 #3
现在我想添加一个不传递给Grid的选项。我选择"Rotation"来改变标题行的文字旋转。
我再次清除了先前的定义和默认选项。注意列表中包含"Rotation" -> 90 Degree。
ClearAll[customTabular]
Options[customTabular] =
{Background -> {{{White, Pink}}},
Dividers -> {All, {2 -> True}},
ItemSize -> {1 -> 5},
Alignment -> {Center, {1 -> Top}},
Frame -> True,
FrameStyle -> Thickness[2],
ItemStyle -> Directive[FontSize -> 15, Black, Bold],
"Rotation" -> 90 Degree};
现在我需要一种方法来使用这个新选项,并且我需要一种方法来防止这个选项被发送到Grid:
我首先将任何显式选项加入Options@customTabular 列表的前面,再次覆盖默认值。
customTabular[data_, opts : OptionsPattern[]] :=
Grid[MapAt[Rotate[#, OptionValue["Rotation"]] & /@ # &, data, 1],
Sequence @@ FilterRules[{opts} ~Join~ Options@customTabular, Options@Grid]
] // Text
例子:
SetOptions[customTabular, Background -> {{{LightBrown, LightYellow}}}];
customTabular[data,
Dividers -> All,
"Rotation" -> -90 Degree,
FrameStyle -> {Darker@Red, Thick}
]