It looks like R has some cool visualization function for clusters that gives output like this:

enter image description here

The input is 2D Points and labels for them. How can i get same visualization in Python?


In Wolfram Language you may use FindClusters to identify the clusters, ConvexHullMesh to calculate the convex hull of the clusters, and ListPlot with the Prolog option and Labeled to display.

First we will collect some example data from the USA "AdministrativeDivision" states. The "Name" property includes the county so this is removed with StringDelete.

data = Select[FreeQ[_Missing]]@EntityValue[
    EntityClass["AdministrativeDivision", {"ParentRegion" -> Entity["Country", "UnitedStates"]}],
    {"HomeOwnershipRate", "HealthInsuranceCoverageRate", "Name"}];
data = MapAt[StringDelete[", United States"], {All, -1}]@data;
{70.7% , 85.2%, "Alabama"}

For each state we get two "Percent" Quantity objects and the state name.

We can FindClusters on this list by using all but the last item in each list (Most) for the cluster algorithm but returning the entire list (Identity), which includes the name, as the cluster item.

clusters = FindClusters[Rule @@ Through[{Most, Identity}@#] & /@ data, Method -> "MeanShift"];

The hulls of clusters with ConvexHullMesh.

hulls = ConvexHullMesh /@ Map[Most] /@ clusters;

Then ListPlot clusters with each point Labeled while using Prolog to plot the hulls beneath the points.

 Map[Labeled[Most@#, Last@#] &] /@ clusters,
 PlotStyle -> ColorData[110],
 PlotTheme -> "Detailed",
 FrameLabel -> {"HomeOwnershipRate", "HealthInsuranceCoverageRate"},
 Prolog -> {
    {ColorData[110] @@ #2, 
      EdgeForm[{Thin, ColorData[110] @@ #2}], #1} &,

enter image description here

The default behaviour is to automatically use Tooltip in places where labels would overcrowd.

Hope this helps.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.