Julia: scatter plot with different colors (using either ColorGradient or other continuous color encodings)

Viewed 1273

Very simple question but I'm not very familiar with the way the ColorGradient type works so I thought I'd ask here.

Say I have some x, y data that I want to plot in the standard way with scatter(x,y) and I want to color the dots with their unique colors based on a color map determined by a color gradient (see code below):

using Plots
C(g::ColorGradient) = RGB[g[z] for z=LinRange(0,1,30)]
g = :inferno

(source: https://github.com/JuliaPlots/ExamplePlots.jl/blob/master/notebooks/cgrad.ipynb)

How would I set up my color gradient object and then use it to map each of my (x,y) pairs to a different one of the colors in the color gradient, using the scatter() function?

My guess is something like:

x, y = (rand(10), rand(10))
using Plots
C(g::ColorGradient) = RGB[g[z] for z=LinRange(0,1,10)]
g = :blue

scatter(x,y,c=cgrad(g)|> C)

I just tried that and it works, but I don't really get why...what is with this |> C notation??

1 Answers

The shortest way to get the plot is:

using Plots, Colors
scatter(x,y,c=colormap("Blues",10))

Another colormap worth mentioning is to have very different colors of points:

scatter(x,y,c=distinguishable_colors(10))

The |> operator is just passing an argument to a function so you can write either f(x) or x |> f. Consider the example below:

julia> f(a,b=5) = a+b;

julia> 7 |> f
12
Related