How to Draw a Box Plot in Julia
English Translation
Description
To draw a box plot, the statistical visualization package StatsPlots.jl
must be used.
boxplot([data], labels=[label])
Code
using StatsPlots
x = rand(0:100, 100)
y = rand(50:100, 100)
z = cat(x,y, dims=1)
boxplot(x, label="x")
boxplot!(y, label="y")
boxplot!(z, label="z")
Or boxplot([x,y,z], label=["x" "y" "z"])
will draw the same figure. Note that there should be no commas in lable
. That is, it needs to be an array, not an $3 \times 1$ vector as in $1 \times 3$.
x-axis tick
If you want to represent the x-axis ticks with strings,
boxplot([x, y, z], xticks=(1:3, ["x", "y", "z"]), label=["x" "y" "z"])
Or the code below will also draw the same figure. The difference is how the actual coordinates are. In the code above, the actual x-coordinates where each box is drawn are 1, 2, 3, but it just appears with the tick values as x, y, z. The code below actually draws boxes on the “x”, “y”, “z” coordinates.
Drawing with a 2D array
a = rand(100, 3)
boxplot(a, xticks=(1:3, ["x", "y", "z"]), label=["x" "y" "z"])
Drawing with a data frame
Data frames cannot be drawn on their own and need to be converted to an array.
using MLDatasets
using DataFrames
df = Iris().features
boxplot(Array(df), xticks=(1:4, names(df)), label=reshape(names(df), (1,4)))
Average
There is no separate option to display the average. Use scatter
to plot it.
using Statistics
boxplot(fill("x", length(x)), x, labels="x")
boxplot!(fill("y", length(y)), y, labels="y")
boxplot!(fill("z", length(z)), z, labels="z")
scatter!(["x", "y", "z"], [mean(x), mean(y), mean(z)], color=palette(:default)[1:3], label="")
Or the following code also draws the same picture.
boxplot([x, y, z], xticks=(1:3, ["x", "y", "z"]), label=["x" "y" "z"])
scatter!([1, 2, 3], [mean(x), mean(y), mean(z)], color=palette(:default)[1:3], label="")
Environment
- OS: Windows11
- Version: Julia 1.9.0, Plots v1.38.12, StatsPlots v0.15.5, DataFrames v1.5.0, MLDatasets v0.7.11