Dan.phi
Dan.phi

Reputation: 75

Labelling and specifying bins in histograms in Julia

I'm trying to plot a histogram in Julia. For illustrative purposes, in the example below I plot age, which ranges from 0 to 100.

age = 100*rand(1000,1)
histogram(age, xlabel = "Age", bins = range(0,100, step = 5),
            xticks = 0:5:100, leg = false)

Ideally I'd want to:

  1. Have the first bin include all values smaller than 20, and the last all greater than 60. The other bins should be just as above, step = 5.

  2. Be able to label the bins, in particular to have < 20 and > 60.

Is there any way to do this?

Upvotes: 5

Views: 2256

Answers (1)

Nils Gudat
Nils Gudat

Reputation: 13800

I'm assuming you're using the Plots plotting package (it's good to make this explicitly in your question, as there are many mature plotting packages in Julia with different syntax and functionality).

To your first question, it's useful to clamp your age vector, so that all values below 20 are set to 19, and all values above 60 are set to 61.

On the second point, you can just set the xticks including labels explicitly:

julia> histogram(clamp.(age, 19, 61), bins = 10; xlabel = "Age", leg = false,
                 xticks = ([17.5; 20:5:60; 62.5], ["<20"; 20:5:60; ">60"]), xrot = 45)

gives:

enter image description here

Upvotes: 4

Related Questions