ortatrit
ortatrit

Reputation: 41

How to color a scatter plot of two vectors (x,y) according to a third vector (z)

I would like to color points (x,y) in a scatter plot according to the value of z (with the same index).

Upvotes: 4

Views: 94

Answers (2)

niczky12
niczky12

Reputation: 5063

In addition to the answer above, if you're looking for discrete markers, you should use the group argument scatter(x, y, group=z):

julia> using Plots, Random

julia> Random.seed!(1234)


julia> k = 10
10

julia> x, y  = rand(k), rand(k);

julia> z = rand(1:3, k)
10-element Vector{Int64}:
 1
 2
 1
 2
 3
 1
 2
 3
 3
 2

julia> scatter(x, y, group=z)

enter image description here

This works with string-like values too:

julia> z2 = rand('a':'c', k)
10-element Vector{Char}:
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)

julia> scatter(x, y, group=z2)

enter image description here

Upvotes: 1

Ashlin Harris
Ashlin Harris

Reputation: 422

I've adapted this relevant example using the marker_z argument from the Julia Discourse:

julia> using Plots, Random

julia> Random.seed!(1234)
TaskLocalRNG()

julia> k = 5;

julia> x = rand(k)
5-element Vector{Float64}:
 0.32597672886359486
 0.5490511363155669
 0.21858665481883066
 0.8942454282009883
 0.35311164439921205

julia> y = rand(k)
5-element Vector{Float64}:
 0.39425536741585077
 0.9531246272848422
 0.7955469475347194
 0.4942498668904206
 0.7484150218874741

julia> z = rand(k)
5-element Vector{Float64}:
 0.5782319465613976
 0.7279350012266056
 0.007448006132865004
 0.19937661409915552
 0.4392431254532684

julia> scatter(x, y, marker_z=z)

This will color the points (x,y) in a gradient according to the value of z.

Scatter plot with marker_z

Upvotes: 4

Related Questions