Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

julia

plots.jl

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

like image 683
ortatrit Avatar asked Oct 20 '25 14:10

ortatrit


2 Answers

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

like image 73
Ashlin Harris Avatar answered Oct 23 '25 06:10

Ashlin Harris


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

like image 45
niczky12 Avatar answered Oct 23 '25 08:10

niczky12



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!