Julia 中的多个直方图使用 Plots.jl

Multiple histograms in Julia using Plots.jl

我正在处理大量观察结果,为了真正了解它,我想使用 Plots.jl 绘制直方图 我的问题是如何在一个图中绘制多个直方图,因为这真的很方便。我已经尝试了多种方法,但我对 julia 中的不同绘图源有点困惑(plots.jl、pyplot、gadfly 等)。

我不知道 post 我的一些代码是否对我有帮助,因为这是一个更笼统的问题。但我很乐意 post 它,如果需要的话。

an example 就是这样做的:

using Plots
pyplot()

n = 100
x1, x2 = rand(n), 3rand(n)

# see issue #186... this is the standard histogram call
# our goal is to use the same edges for both series
histogram(Any[x1, x2], line=(3,0.2,:green), fillcolor=[:red :black], fillalpha=0.2)

我在示例的 the Plots.jl repo, found this related issue and followed the links 中查找了 "histograms"。

对于Plots,在一个图中显示多个系列有两种可能性:

首先,您可以使用矩阵,其中每一列构成一个单独的系列:

a, b, c = randn(100), randn(100), randn(100)
histogram([a b c])

此处,hcat用于连接向量(注意空格而不是逗号)。

这相当于

histogram(randn(100,3))

您可以使用行矩阵将选项应用于单个系列:

histogram([a b c], label = ["a" "b" "c"])

(再次注意空格而不是逗号)

其次,您可以使用 plot! 及其变体来更新之前的情节:

histogram(a)  # creates a new plot
histogram!(b) # updates the previous plot
histogram!(c) # updates the previous plot

或者,您可以指定要更新的绘图:

p = histogram(a) # creates a new plot p
histogram(b)     # creates an independent new plot
histogram!(p, c) # updates plot p

如果您有多个子图,这很有用。

编辑:

按照 Felipe Lema 的链接,您可以实现共享边的直方图的方法:

using StatsBase
using PlotRecipes

function calcbins(a, bins::Integer)
    lo, hi = extrema(a)
    StatsBase.histrange(lo, hi, bins) # nice edges
end

calcbins(a, bins::AbstractVector) = bins

@userplot GroupHist 

@recipe function f(h::GroupHist; bins = 30)
    args = h.args
    length(args) == 1 || error("GroupHist should be given one argument")
    bins = calcbins(args[1], bins)
    seriestype := :bar
    bins, mapslices(col -> fit(Histogram, col, bins).weights, args[1], 1)
end

grouphist(randn(100,3))

编辑 2:

因为速度更快,我更改了配方以使用 StatsBase.fit 创建直方图。