如何使用 Plots.jl 根据 z 中的值为 (x,y) 散点图着色?

How do you color (x,y) scatter plots according to values in z using Plots.jl?

使用 Julia 中的 Plots.jl 包,我可以使用各种后端来制作基于两个向量 xy

的散点图
k = 100
x = rand(k)
y = rand(k)
scatter(x, y)

我找不到有关如何根据某个长度 k 向量 z 为它们着色的信息。你是怎么做到的?

我本以为如果您将 k 定义为颜色符号的向量,这会起作用:scatter(x, y, markercolors=k),但它似乎不起作用。但是,如本例所示,一次添加一个:

using Plots

xs = rand(10)
ys = rand(10)
ks = randbool(10) + 1 # 1 or 2
mcols = [:red, :blue]  # together, mcols[ks] is the `k` in the question

p = scatter(xs[ks .== 1], ys[ks .== 1], markercolor=mcols[1])
for k = 2:length(mcols)
    scatter!(xs[ks .== k], ys[ks .== k], markercolor=mcols[k])
end
p

以下方法将比 jverzani 的方法好得多(您不想为每个数据点创建一个新系列)。绘图可以使用一些额外的爱来手动定义颜色向量,但现在渐变得到很好的支持,所以你可以利用它。

using Plots
pyplot(size=(400,200), legend=false)  # set backend and set some session defaults

scatter(rand(30),
        m = ColorGradient([:red, :green, :blue]),  # colors are defined by a gradient
        zcolor = repeat( [0,0.5,1], 10) # sample from the gradient, cycling through: 0, 0.5, 1
       )

如果向量 z 中的元素是分类值而不是连续值,您可能需要考虑对绘图调用使用 group 参数,如下所示:

using Plots

# visualize x and y colouring points based on category z
scatter(x, y, group=z)