Still learning the new DataSet feature, I would like to create a ListPlot where the color of the points is to be determined by a column in the dataset. Here is what I have:

(* import and set column names *)
iris = SemanticImport["http://aima.cs.berkeley.edu/data/iris.csv"];
iris = iris[All, <|
    "SepalLength" -> 1, "SepalWidth" -> 2, 
    "PetalLength" -> 3, "PetalWidth" -> 4, "Species" -> 5

(* ListPlot *)
iris[ListPlot, {"PetalLength", "SepalWidth"}]

Now I have no idea how to set the color according the "Species" column. The documentation did not help. Ideally, the plot has a legend mapping colors to species.

Any hint appreciated!

color[s_] := Switch[s, "setosa", Red, "versicolor", Green, "virginica", Blue];
              BaseStyle->{PointSize[.015] ,FontSize->16},
              PlotLabel->"Iris Data"]&, 
 {"PetalLength", "SepalWidth","Species"}]

enter image description here

  • $\begingroup$ Great solution! $\endgroup$
    – Karsten W.
    Oct 23 '14 at 13:51
  • $\begingroup$ @KarstenW., thank you for the Accept. $\endgroup$
    – kglr
    Oct 23 '14 at 13:57
  • $\begingroup$ Great code. I am using a lot and would like to add a tooltip for each point which displays the values {x,y} but does not succeed to. Thanks for your help. $\endgroup$
    – Porty
    Oct 13 '17 at 5:54
  • $\begingroup$ @Porty thank you for kind words. I am not able to test but doesn't iris[ListPlot[Style[Tooltip[{#, #2}], color @ #3]&@@@# , ... ] work? $\endgroup$
    – kglr
    Oct 13 '17 at 6:54
ListPlot[iris[GroupBy[Key["Species"]],All,{"PetalLength", "SepalWidth"}],
   PlotLegends -> "Expressions" ]

enter image description here


Ok, I found a solution to my question.

color[s_] := Switch[s, "setosa", Red, "versicolor", Green, "virginica", Blue];
    List /@ Normal@iris[All, {"SepalLength", "PetalWidth"}],
    PlotStyle -> Normal@(color /@ iris[All, "Species"]),
    PlotLegends -> SwatchLegend @@ 
          Transpose[({color[#], #} & /@ iris[Union, "Species"])]

However, if you have a more Queryish answer, I will upvote and accept yours...


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.