使用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 创建直方图。