logo

How to Use Hexadecimal RGB Codes (HEX) in Julia 📂Julia

How to Use Hexadecimal RGB Codes (HEX) in Julia

Code

The package provided for handling colors in Julia is Colors.jl. By loading the visualization package Plots.jl, one can also use the functionality within Colors.jl. Color codes representing the RGB space, such as RGB, BGR, RGB24, RGBX, XRGB, are supported and are subtypes of AbstractRGB. RGBA is RGB with added transparency.

julia> using Plots

julia> subtypes(AbstractRGB)
5-element Vector{Any}:
 BGR
 RGB
 RGB24
 RGBX
 XRGB

julia> subtypes(AbstractRGBA)
2-element Vector{Any}:
 BGRA
 RGBA

Strings

By inputting a string such as "#FF0000" as a color keyword in the plot() function, one can use the HEX code, a hexadecimal RGB code. As one can see below, the reason why string input is also feasible seems to be because plot() automatically parses the string.

using Plots

r = "#FF0000"      # R빨간색 RGB(255, 0, 0)의 6자리 HEX 코드
g = "#00FF0033"    # 투명도가 0.2인 초록색 RGBA(0, 255, 0, 0.2)의 8자리 HEX 코드
p = "#80F"         # 보라색 RGB(255, 0, 136)의 3자리 HEX 코드

plot([1 2 3; 2 3 4], ones(2, 3), fillrange = 2,
        fillcolor = [r g p],
        label = [r g p])

Parsing

HEX codes can be parsed in the form of colorant"#FF0000".

julia> r = colorant"#FF0000"      # R빨간색 RGB(255, 0, 0)의 6자리 HEX 코드
RGB{N0f8}(1.0,0.0,0.0)

julia> g = colorant"#00FF0033"    # 투명도가 0.2인 초록색 RGBA(0, 255, 0, 0.2)의 8자리 HEX 코드
RGBA{N0f8}(0.0,1.0,0.0,0.2)

julia> p = colorant"#80F"         # 보라색 RGB(255, 0, 136)의 3자리 HEX 코드
RGB{N0f8}(0.533,0.0,1.0)

julia> plot([1 2 3; 2 3 4], ones(2, 3), fillrange = 2,
            fillcolor = [r g p])

It can also be parsed as parse(RGB, "#FF0000").

julia> parse(RGB, "#FF0000")
RGB{N0f8}(1.0,0.0,0.0)

julia> parse(RGBA, "#FF000080")
RGBA{N0f8}(1.0,0.0,0.0,0.502)

Getting Color Names

The hex() function returns the color’s HEX code as a string.

julia> hex(colorant"red")
"FF0000"

julia> hex(colorant"rgb(0, 255, 128)")
"00FF80"

julia> hex(RGBA(1, 0.5, 0, 0.5), :RRGGBB)
"FF8000"

julia> hex(RGBA(1, 0.5, 0, 0.5), :RRGGBBAA)
"FF800080"

julia> hex(HSV(30,1.0,1.0), :AARRGGBB)
"FFFF8000"

See Also

Environment

  • OS: Windows11
  • Version: Julia 1.9.4, Plots v1.39.0, Colors v0.12.10, FixedPointNumbers v0.8.4

See Also