Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labeling vertices of a polygon in Mathematica

Given a set of points in the plane T={a1,a2,...,an} then Graphics[Polygon[T]] will plot the polygon generated by the points. How can I add labels to the polygon's vertices? Have merely the index as a label would be better then nothing. Any ideas?

like image 540
Dror Avatar asked Aug 03 '11 07:08

Dror


People also ask

What is used to Labelled vertex?

A labeling of a graph is a function f from the vertex set to some subset of the natural numbers. The image of a vertex is called its label. We assign the label |f(u) - f(v)| to the edge incident with vertices u and v. In a 4-equitable labeling, the image of f is the set 10, 1, 2, 3l.


2 Answers

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

To add point also

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

update:

Use the index:

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

like image 144
Nasser Avatar answered Sep 20 '22 23:09

Nasser


Nasser's version (update) uses pattern matching. This one uses functional programming. MapIndexed gives you both the coordinates and their index without the need for Position to find it.

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

or, if you don't like MapIndexed, here's a version with Apply (at level 1, infix notation @@@).

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

This can be expanded to arbitrary labels as follows:

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

like image 37
Sjoerd C. de Vries Avatar answered Sep 17 '22 23:09

Sjoerd C. de Vries