贝利撒留给出了基本方法。我将介绍一种高级方法,因为你看起来很渴望学习。
首先我要说的是,我看到了我认为对您的代码的简化,并且我做了它们,希望没有错误。
我将在下面的插图中使用此示例数据:
data = Prepend[
RandomInteger[99, {5, 12}],
DateString[{1, #}, "MonthName"] & /@ Range@12
];
Goals
-
由于使用的主要函数是Grid
允许向其传递选项是有意义的。
-
您有一系列定义您的表的选项。我希望能够方便地更改这些。
-
我想要自定义选项不被理解的可能性Grid
.
执行
Goal #1
论证模式opts:OptionsPattern[]
添加,它匹配任何序列Option -> Setting
参数,并命名它opts
. (See: 选项模式 http://reference.wolfram.com/mathematica/ref/OptionsPattern.html了解更多。)然后,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]
Goal #2
定义表格格式的选项可以与函数体分开。这将使它们可以方便地更改或引用。我首先清除之前的定义ClearAll
。然后我设置默认Options http://reference.wolfram.com/mathematica/ref/Options.html for customTabular
:
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 http://reference.wolfram.com/mathematica/ref/SetOptions.html。例子:
SetOptions[customTabular,
Background -> {{{LightMagenta, LightOrange}}}
];
customTabular[data]
Goal #3
现在我想添加一个选项not传递给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
Example:
SetOptions[customTabular, Background -> {{{LightBrown, LightYellow}}}];
customTabular[data,
Dividers -> All,
"Rotation" -> -90 Degree,
FrameStyle -> {Darker@Red, Thick}
]