【问题标题】:Labeling vertices of a polygon in Mathematica在 Mathematica 中标记多边形的顶点
【发布时间】:2011-08-03 07:14:35
【问题描述】:

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

【问题讨论】:

    标签: wolfram-mathematica plot


    【解决方案1】:
    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}]}
      }
     ]
    

    【讨论】:

    • 这真是太好了。几乎是我所追求的。如何更改您的示例,并获取顶点索引作为标签而不是坐标?提前致谢!
    • 哇!这真是太棒了!你能补充一些解释有什么魔力吗?
    • 我们怎样才能去掉包裹标签的大括号?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您可以为此利用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]]}]
      

      【讨论】:

        猜你喜欢
        • 2018-07-24
        • 2013-11-16
        • 2016-02-11
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 2014-09-05
        • 2023-03-12
        • 2015-11-23
        相关资源
        最近更新 更多