Dean Schulze
Dean Schulze

Reputation: 10303

How can I get multiple histogram plots from a dataframe in Julia

I have a julia dataframe and I want to plot each column as a histogram, but only the last one is finally displayed. I'm using StatsPlot. Is there a better plotting package to use for this?

using StatsPlots
@df df histogram(:x1)
@df df histogram(:x2)
@df df histogram(:x3)
@df df histogram(:x4)
@df df histogram(:x5)
@df df histogram(:x6)
@df df histogram(:x7)
@df df histogram(:x8)
@df df histogram(:x9)
@df df histogram(:x10)
@df df histogram(:x11)
@df df histogram(:x12)
@df df histogram(:x13)
@df df histogram(:x14)

Upvotes: 4

Views: 1155

Answers (1)

Nils Gudat
Nils Gudat

Reputation: 13800

As Bogumil says in his comment it's not entirely clear what output you're after, but I can see two possible ways:

If you want to have a separate subplot for each column, you can broadcast the histogram call over the columns you want, example:

julia> using Plots, DataFrames

julia> df = DataFrame([randn(1_000) .+ i for i ∈ 1:10], :auto);

julia> plot(histogram.(eachcol(df))...)

which gives

enter image description here

Alternatively if you want all the histograms overlaid you can use histogram! (note the bang) which modifies an existing plot:

julia> plot(); last(histogram!.(eachcol(df)))

enter image description here

Note that here I've called plot() first as every histogram! call overrides an existing (global) plot object, so if I had called this after creating the multiple-subplots version above the additional histograms would have been plotted on the existing previous plot.

Both of these suggestions are going for brevity and might make it harder to fine tune things like labels, titles, etc. and I often find loops a clearer way to write these things, but hopefully they give you an idea of how what you're after can be done relatively easily (and without StatsPlots, all of this is plain Plots)

Upvotes: 4

Related Questions