【发布时间】:2011-08-03 07:14:35
【问题描述】:
给定平面上的一组点T={a1,a2,...,an} 然后Graphics[Polygon[T]] 将绘制由这些点生成的多边形。如何将标签添加到多边形的顶点?仅将索引作为标签会比没有更好。有什么想法吗?
【问题讨论】:
给定平面上的一组点T={a1,a2,...,an} 然后Graphics[Polygon[T]] 将绘制由这些点生成的多边形。如何将标签添加到多边形的顶点?仅将索引作为标签会比没有更好。有什么想法吗?
【问题讨论】:
pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
Graphics[
{{LightGray, Polygon[pts]},
{pts /. {x_, y_} :> Text[Style[{x, y}, Red], {x, y}]}}
]
还要加点
pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
Graphics[
{{LightGray, Polygon[pts]},
{pts /. {x_, y_} :> Text[Style[{x, y}, Red], {x, y}, {0, -1}]},
{pts /. {x_, y_} :> {Blue, PointSize[0.02], Point[{x, y}]}}
}
]
更新:
使用索引:
pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
Graphics[
{{LightGray, Polygon[pts]},
{pts /. {x_, y_} :>
Text[Style[Position[pts, {x, y}], Red], {x, y}, {0, -1}]}
}
]
【讨论】:
Nasser's version (update) 使用pattern matching。这个使用functional programming。 MapIndexed 为您提供坐标和它们的索引,而无需 Position 找到它。
pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
Graphics[
{
{LightGray, Polygon[pts]},
MapIndexed[Text[Style[#2[[1]], Red], #1, {0, -1}] &, pts]
}
]
或者,如果您不喜欢MapIndexed,这里有一个带有Apply 的版本(在级别1,中缀符号@@@)。
pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
idx = Range[Length[pts]];
Graphics[
{
{LightGray, Polygon[pts]},
Text[Style[#2, Red], #1, {0, -1}] & @@@ ({pts, idx}\[Transpose])
}
]
这可以扩展为任意标签,如下所示:
pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
idx = {"One", "Two", "Three"};
Graphics[
{
{LightGray, Polygon[pts]},
Text[Style[#2, Red], #1, {0, -1}] & @@@ ({pts, idx}\[Transpose])
}
]
【讨论】:
您可以为此利用GraphPlot 的选项。示例:
c = RandomReal[1, {3, 2}]
g = GraphPlot[c, VertexLabeling -> True, VertexCoordinateRules -> c];
Graphics[{Polygon@c, g[[1]]}]
这样你也可以使用VertexLabeling -> Tooltip,如果你愿意,也可以使用VertexRenderingFunction。如果您不希望边缘重叠,您可以将EdgeRenderingFunction -> None 添加到GraphPlot 函数中。示例:
c = RandomReal[1, {3, 2}]
g = GraphPlot[c, VertexLabeling -> All, VertexCoordinateRules -> c,
EdgeRenderingFunction -> None,
VertexRenderingFunction -> ({White, EdgeForm[Black], Disk[#, .02],
Black, Text[#2, #1]} &)];
Graphics[{Brown, Polygon@c, g[[1]]}]
【讨论】: