在Mathematica中标注多边形的顶点

时间:2011-08-03 07:14:35

标签: wolfram-mathematica plot

给定平面T={a1,a2,...,an}中的一组点,然后Graphics[Polygon[T]]将绘制由点生成的多边形。如何在多边形的顶点添加标签?只有索引作为标签会比没有更好。有什么想法吗?

3 个答案:

答案 0 :(得分:9)

pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
Graphics[
 {{LightGray, Polygon[pts]},
  {pts /. {x_, y_} :> Text[Style[{x, y}, Red], {x, y}]}}
 ]

enter image description here

还要添加点

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}]}}
  }
 ]

enter image description here

更新:

使用索引:

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}]}
  }
 ]

enter image description here

答案 1 :(得分:7)

Nasser's version (update)使用pattern matching。这个使用functional programmingMapIndexed为您提供坐标及其索引,而无需Position找到它。

pts = {{1, 0}, {0, Sqrt[3]}, {-1, 0}};
Graphics[
 {
  {LightGray, Polygon[pts]},
  MapIndexed[Text[Style[#2[[1]], Red], #1, {0, -1}] &, pts]
  }
 ]

enter image description here

或者,如果您不喜欢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])
  }
 ]

enter image description here

答案 2 :(得分:0)

您可以利用GraphPlot的选项来实现此目的。例如:

c = RandomReal[1, {3, 2}]
g = GraphPlot[c, VertexLabeling -> True, VertexCoordinateRules -> c];

Graphics[{Polygon@c, g[[1]]}]

这样,如果您愿意,也可以使用VertexLabeling -> TooltipVertexRenderingFunction。如果您不希望边缘重叠,可以将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]]}]

enter image description here