Skip to content

Commit 552328c

Browse files
Fix UnitfulExt for PGFPlotsX take 2 (#4747)
* tests and migrate unitformat * fix tests * format * fix tests * adjust empty label case * add imports * add compat * ditch 1.6 * Revert "ditch 1.6" This reverts commit 1f0ce95. * change imports * fix ci config
1 parent dc3f40e commit 552328c

File tree

8 files changed

+154
-102
lines changed

8 files changed

+154
-102
lines changed

.github/workflows/ci.yml

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ on:
55
branches: [master]
66
pull_request:
77

8-
concurrency:
8+
concurrency:
99
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
1010
cancel-in-progress: true
1111

@@ -29,18 +29,21 @@ jobs:
2929
matrix:
3030
version:
3131
- '1.6' # LTS (minimal declared julia compat in `Project.toml`)
32-
- '1.8' # latest stable
32+
- '1.9' # latest stable
3333
os: [ubuntu-latest, windows-latest, macos-latest]
3434
arch: [x64]
3535
include:
3636
- os: ubuntu-latest
3737
prefix: xvfb-run # julia-actions/julia-runtest/blob/master/README.md
3838
- os: ubuntu-latest
3939
prefix: xvfb-run
40-
version: '1.7' # only test intermediate release on `ubuntu` to spare resources
40+
version: '1.7' # only test intermediate release on `ubuntu` to spare resources
4141
- os: ubuntu-latest
4242
prefix: xvfb-run
43-
version: '~1.9.0-0' # upcoming julia version, next `rc`
43+
version: '1.8' # only test intermediate release on `ubuntu` to spare resources
44+
# - os: ubuntu-latest
45+
# prefix: xvfb-run
46+
# version: '~1.9.0-0' # upcoming julia version, next `rc`
4447
- os: ubuntu-latest
4548
prefix: xvfb-run
4649
version: 'nightly'

Project.toml

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
2121
Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
2222
PlotThemes = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a"
2323
PlotUtils = "995b91a9-d308-5afd-9ec6-746e21dbc043"
24+
PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a"
2425
Preferences = "21216c6a-2e73-6563-6e65-726566657250"
2526
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
2627
REPL = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
@@ -32,14 +33,28 @@ RelocatableFolders = "05181044-ff0b-4ac5-8273-598c1e38db00"
3233
Requires = "ae029012-a4dd-5104-9daa-d747884805df"
3334
Scratch = "6c6a2e73-6563-6170-7368-637461726353"
3435
Showoff = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
35-
PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a"
3636
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
3737
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
3838
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
3939
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
4040
UnicodeFun = "1cfade01-22cf-5700-b092-accc4b62d6e1"
41+
UnitfulLatexify = "45397f5d-5981-4c77-b2b3-fc36d6e9b728"
4142
Unzip = "41fe7b60-77ed-43a1-b4f0-825fd5a5650d"
4243

44+
[weakdeps]
45+
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
46+
GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
47+
IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a"
48+
ImageInTerminal = "d8c32880-2388-543b-8c61-d9f865259254"
49+
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
50+
51+
[extensions]
52+
FileIOExt = "FileIO"
53+
GeometryBasicsExt = "GeometryBasics"
54+
IJuliaExt = "IJulia"
55+
ImageInTerminalExt = "ImageInTerminal"
56+
UnitfulExt = "Unitful"
57+
4358
[compat]
4459
Contour = "0.5 - 0.6"
4560
FFMPEG = "0.2 - 0.4"
@@ -61,6 +76,7 @@ PlotUtils = "1"
6176
PlotlyBase = "0.7 - 0.8"
6277
PlotlyJS = "0.18"
6378
PlotlyKaleido = "1"
79+
PrecompileTools = "1"
6480
Preferences = "1"
6581
PyPlot = "2"
6682
PythonPlot = "1"
@@ -71,20 +87,13 @@ RelocatableFolders = "0.3, 1"
7187
Requires = "1"
7288
Scratch = "1"
7389
Showoff = "0.3.1, 1"
74-
PrecompileTools = "1"
7590
StatsBase = "0.33"
7691
UnicodeFun = "0.4"
7792
UnicodePlots = "3.4"
93+
UnitfulLatexify = "1"
7894
Unzip = "0.1 - 0.2"
7995
julia = "1.6"
8096

81-
[extensions]
82-
FileIOExt = "FileIO"
83-
GeometryBasicsExt = "GeometryBasics"
84-
IJuliaExt = "IJulia"
85-
ImageInTerminalExt = "ImageInTerminal"
86-
UnitfulExt = "Unitful"
87-
8897
[extras]
8998
Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595"
9099
Colors = "5ae59095-9a9b-59fe-a467-6f913c188581"
@@ -121,10 +130,3 @@ VisualRegressionTests = "34922c18-7c2a-561c-bac1-01e79b2c4c92"
121130

122131
[targets]
123132
test = ["Aqua", "Colors", "Distributions", "FileIO", "FilePathsBase", "FreeType", "Gaston", "GeometryBasics", "Gtk", "ImageMagick", "Images", "InspectDR", "LibGit2", "OffsetArrays", "PGFPlotsX", "PlotlyJS", "PlotlyBase", "PyPlot", "PythonPlot", "PlotlyKaleido", "HDF5", "RDatasets", "SentinelArrays", "StableRNGs", "StaticArrays", "StatsPlots", "Test", "TestImages", "UnicodePlots", "Unitful", "VisualRegressionTests"]
124-
125-
[weakdeps]
126-
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
127-
GeometryBasics = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
128-
IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a"
129-
ImageInTerminal = "d8c32880-2388-543b-8c61-d9f865259254"
130-
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"

ext/UnitfulExt.jl

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ module UnitfulExt
66
import Plots: Plots, @ext_imp_use, @recipe, PlotText, Subplot, AVec, AMat, Axis
77
import RecipesBase
88
@ext_imp_use :import Unitful Quantity unit ustrip Unitful dimension Units NoUnits LogScaled logunit MixedUnits Level Gain uconvert
9+
import LaTeXStrings: LaTeXString
10+
import Latexify: latexify
11+
using UnitfulLatexify
912

1013
const MissingOrQuantity = Union{Missing,<:Quantity,<:LogScaled}
1114

@@ -214,12 +217,38 @@ append_unit_if_needed!(attr, key, u) =
214217
# dispatch on the type of `label`
215218
append_unit_if_needed!(attr, key, label::ProtectedString, u) = nothing
216219
append_unit_if_needed!(attr, key, label::UnitfulString, u) = nothing
217-
append_unit_if_needed!(attr, key, label::Nothing, u) =
218-
(attr[key] = UnitfulString(string(u), u))
220+
function append_unit_if_needed!(attr, key, label::Nothing, u)
221+
attr[key] = if attr[:plot_object].backend == Plots.PGFPlotsXBackend()
222+
UnitfulString(LaTeXString(latexify(u)), u)
223+
else
224+
UnitfulString(string(u), u)
225+
end
226+
end
219227
function append_unit_if_needed!(attr, key, label::S, u) where {S<:AbstractString}
220228
isempty(label) && return attr[key] = UnitfulString(label, u)
221-
attr[key] =
222-
UnitfulString(S(format_unit_label(label, u, get(attr, :unitformat, :round))), u)
229+
if attr[:plot_object].backend == Plots.PGFPlotsXBackend()
230+
attr[key] = UnitfulString(
231+
LaTeXString(
232+
format_unit_label(
233+
label,
234+
latexify(u),
235+
get(attr, Symbol(attr[:letter], :unitformat), :round),
236+
),
237+
),
238+
u,
239+
)
240+
else
241+
attr[key] = UnitfulString(
242+
S(
243+
format_unit_label(
244+
label,
245+
u,
246+
get(attr, Symbol(attr[:letter], :unitformat), :round),
247+
),
248+
),
249+
u,
250+
)
251+
end
223252
end
224253

225254
#=============================================
@@ -237,6 +266,7 @@ const UNIT_FORMATS = Dict(
237266
:slashcurly => (" / {", "}"),
238267
:slashangle => (" / <", ">"),
239268
:verbose => " in units of ",
269+
:none => nothing,
240270
)
241271

242272
format_unit_label(l, u, f::Nothing) = string(l, ' ', u)
@@ -293,17 +323,8 @@ function _unit(x)
293323
unit(x)
294324
end
295325

296-
Plots.pgfx_sanitize_string(s::UnitfulString) = begin
297-
tex_str = if (str_unit = string(s.unit)) == s.content
298-
""
299-
else
300-
Plots.pgfx_sanitize_string(s.content)
301-
end
302-
tex_unit = replace(Plots.wrap_power_label(str_unit), ' ' => '~')
303-
if !Plots.pgfx_is_inline_math(tex_unit)
304-
tex_unit = "\\($tex_unit\\)" # force inline math mode
305-
end
306-
isempty(tex_str) ? tex_unit : tex_str * ' ' * tex_unit
326+
function Plots.pgfx_sanitize_string(s::UnitfulString)
327+
UnitfulString(Plots.pgfx_sanitize_string(s.content), s.unit)
307328
end
308329

309330
end # module

src/arg_desc.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,10 @@ const _arg_desc = KW(
195195
:showaxis => (Union{Bool,Symbol,AStr}, "Show the axis. `true`, `false`, `:show`, `:hide`, `:yes`, `:no`, `:x`, `:y`, `:z`, `:xy`, ..., `:all`, `:off`."),
196196
:widen => (Union{Bool,Real,Symbol}, """
197197
Widen the axis limits by a small factor to avoid cut-off markers and lines at the borders.
198-
If set to `true`, scale the axis limits by the default factor of $(default_widen_factor).
198+
If set to `true`, scale the axis limits by the default factor of $(default_widen_factor).
199199
A different factor may be specified by setting `widen` to a number.
200200
Defaults to `:auto`, which widens by the default factor unless limits were manually set.
201201
See also the `scale_limits!` function for scaling axis limits in an existing plot."""),
202202
:draw_arrow => (Bool, "Draw arrow at the end of the axis."),
203+
:unitformat => (Union{Bool,Nothing,Symbol,Char,String,NTuple{<:Union{Char,String}},Function}, """Check examples in https://docs.juliaplots.org/stable/generated/unitfulext_examples/#Unit-formatting"""),
203204
)

src/args.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,7 @@ const _axis_defaults = KW(
519519
:showaxis => true,
520520
:widen => :auto,
521521
:draw_arrow => false,
522+
:unitformat => :round,
522523
)
523524

524525
const _suppress_warnings = Set{Symbol}([

test/test_pgfplotsx.jl

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using Test, Plots, Unitful, LaTeXStrings
2+
13
function create_plot(args...; kwargs...)
24
pl = plot(args...; kwargs...)
35
return pl, repr("application/x-tex", pl)
@@ -119,7 +121,7 @@ with(:pgfplotsx) do
119121
bg = :linen,
120122
xlim = (0, 10),
121123
ylim = (0, 10),
122-
) isa Plot
124+
) isa Plots.Plot
123125
end
124126

125127
@testset "Layout" begin
@@ -128,13 +130,13 @@ with(:pgfplotsx) do
128130
layout = 4,
129131
palette = [:grays :blues :hot :rainbow],
130132
bg_inside = [:orange :pink :darkblue :black],
131-
) isa Plot
133+
) isa Plots.Plot
132134
end
133135

134136
@testset "Polar plots" begin
135137
Θ = range(0, stop = 1.5π, length = 100)
136138
r = abs.(0.1 * randn(100) + sin.(3Θ))
137-
@test plot(Θ, r, proj = :polar, m = 2) isa Plot
139+
@test plot(Θ, r, proj = :polar, m = 2) isa Plots.Plot
138140
end
139141

140142
@testset "Drawing shapes" begin
@@ -170,11 +172,11 @@ with(:pgfplotsx) do
170172
xlim = (0, 1),
171173
ylim = (0, 1),
172174
leg = false,
173-
) isa Plot
175+
) isa Plots.Plot
174176
end
175177

176178
@testset "Histogram 2D" begin
177-
@test histogram2d(randn(10_000), randn(10_000), nbins = 20) isa Plot
179+
@test histogram2d(randn(10_000), randn(10_000), nbins = 20) isa Plots.Plot
178180
end
179181

180182
@testset "Heatmap-like" begin
@@ -188,7 +190,7 @@ with(:pgfplotsx) do
188190
@test axis["colormap name"] == "plots1"
189191
end
190192

191-
@test wireframe(xs, ys, z, aspect_ratio = 1) isa Plot
193+
@test wireframe(xs, ys, z, aspect_ratio = 1) isa Plots.Plot
192194
# TODO: clims are wrong
193195
end
194196

@@ -202,7 +204,7 @@ with(:pgfplotsx) do
202204
p2 = contour(x, y, Z)
203205
p1 = contour(x, y, f, fill = true)
204206
p3 = contour3d(x, y, Z)
205-
@test plot(p1, p2) isa Plot
207+
@test plot(p1, p2) isa Plots.Plot
206208
@test_nowarn Plots._update_plot_object(p3)
207209
# TODO: colorbar for filled contours
208210
end
@@ -214,7 +216,7 @@ with(:pgfplotsx) do
214216
y = t .* sin.(θ)
215217
p1 = plot(x, y, line_z = t, linewidth = 3, legend = false)
216218
p2 = scatter(x, y, marker_z = (x, y) -> x + y, color = :bwr, legend = false)
217-
@test plot(p1, p2) isa Plot
219+
@test plot(p1, p2) isa Plots.Plot
218220
end
219221

220222
@testset "Framestyles" begin
@@ -250,7 +252,7 @@ with(:pgfplotsx) do
250252
u = ones(length(x))
251253
v = cos.(x)
252254
pl = plot(x, y, quiver = (u, v), arrow = true)
253-
@test pl isa Plot
255+
@test pl isa Plots.Plot
254256
# TODO: could adjust limits to fit arrows if too long, but how ?
255257
# mktempdir() do path
256258
# @test_nowarn savefig(pl, path*"arrow.pdf")
@@ -461,4 +463,15 @@ with(:pgfplotsx) do
461463
@test isfile(fn)
462464
end
463465
end
466+
467+
@testset "Unitful interaction" begin
468+
yreg = r"ylabel=\{((?:[^{}]*\{[^{}]*\})*[^{}]*?)\}"
469+
pl1 = plot([1u"s", 2u"s"], [1u"m", 2u"m"], xlabel = "t", ylabel = "diameter")
470+
pl2 = plot([1u"s", 2u"s"], [1u"m/s^2", 2u"m/s^2"])
471+
pl1_tex = String(repr("application/x-tex", pl1))
472+
pl2_tex = String(repr("application/x-tex", pl2))
473+
@test pl1_tex[findfirst(yreg, pl1_tex)] == "ylabel={diameter (\$\\mathrm{m}\$)}"
474+
@test pl2_tex[findfirst(yreg, pl2_tex)] ==
475+
"ylabel={\$\\mathrm{m}\\,\\mathrm{s}^{-2}\$}"
476+
end
464477
end

test/test_quality.jl

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,15 @@
55
Aqua.test_all(
66
Plots;
77
stale_deps = (;
8-
ignore = [:GR, :CondaPkg, :Contour, :Latexify, :LaTeXStrings, :Requires]
8+
ignore = [
9+
:GR,
10+
:CondaPkg,
11+
:Contour,
12+
:Latexify,
13+
:LaTeXStrings,
14+
:Requires,
15+
:UnitfulLatexify,
16+
]
917
),
1018
project_toml_formatting = false, # issues since weak deps
1119
ambiguities = false,

0 commit comments

Comments
 (0)