10
$\begingroup$

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!

$\endgroup$
0

3 Answers 3

9
$\begingroup$
color[s_] := Switch[s, "setosa", Red, "versicolor", Green, "virginica", Blue];
iris[ListPlot[Style[{#,#2},color@#3]&@@@#,
              BaseStyle->{PointSize[.015] ,FontSize->16},
              PlotLabel->"Iris Data"]&, 
 {"PetalLength", "SepalWidth","Species"}]

enter image description here

$\endgroup$
4
  • $\begingroup$ Great solution! $\endgroup$
    – Karsten W.
    Oct 23, 2014 at 13:51
  • $\begingroup$ @KarstenW., thank you for the Accept. $\endgroup$
    – kglr
    Oct 23, 2014 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, 2017 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, 2017 at 6:54
11
$\begingroup$
ListPlot[iris[GroupBy[Key["Species"]],All,{"PetalLength", "SepalWidth"}],
   PlotLegends -> "Expressions" ]

enter image description here

$\endgroup$
1
$\begingroup$

Ok, I found a solution to my question.

color[s_] := Switch[s, "setosa", Red, "versicolor", Green, "virginica", Blue];
ListPlot[
    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...

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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