PolarAxis
|
Страница в процессе перевода. |
PolarAxis — это ось для данных, заданных в полярных координатах, т. е. с радиусом и углом. В настоящее время это экспериментальная функция, поэтому некоторые возможности могут отсутствовать или не работать. Блок PolarAxis (более) активно поддерживает изменения.
Построение графика по PolarAxis
Как и в случае с Axis, изменяемые функции построения двумерных графиков можно использовать непосредственно для PolarAxis. Входные аргументы функций построения графиков будут интерпретироваться в полярных координатах, то есть как угол (в радианах) и радиус. Порядок аргументов можно изменить с помощью ax.theta_as_x.
using CairoMakie
f = Figure(size = (800, 400))
ax = PolarAxis(f[1, 1], title = "Theta as x")
lineobject = lines!(ax, 0..2pi, sin, color = :red)
ax = PolarAxis(f[1, 2], title = "R as x", theta_as_x = false)
scatobject = scatter!(range(0, 10, length=100), cos, color = :orange)
f
Ограничения для PolarAxis
По умолчанию PolarAxis использует po.rlimits[] = (0.0, nothing) и po.thetalimits[] = (0.0, 2pi) для отображения полного круга. Вы можете настроить эти границы для отображения различных срезов PolarAxis. Например, можно ограничить thetalimits меньшим диапазоном, чтобы сгенерировать сектор круга, и далее ограничить rmin с помощью rlimits, чтобы вырезать центр по дуге.
using CairoMakie
f = Figure(size = (600, 600))
ax = PolarAxis(f[1, 1], title = "Default")
lines!(ax, range(0, 8pi, length=300), range(0, 10, length=300))
ax = PolarAxis(f[1, 2], title = "thetalimits", thetalimits = (-pi/6, pi/6))
lines!(ax, range(0, 8pi, length=300), range(0, 10, length=300))
ax = PolarAxis(f[2, 1], title = "rlimits", rlimits = (5, 10))
lines!(ax, range(0, 8pi, length=300), range(0, 10, length=300))
ax = PolarAxis(f[2, 2], title = "both")
lines!(ax, range(0, 8pi, length=300), range(0, 10, length=300))
thetalims!(ax, -pi/6, pi/6)
rlims!(ax, 5, 10)
f
Чтобы внести дополнительные изменения в ориентацию PolarAxis, настройте ax.theta_0 и ax.direction. В этом случае настраивается интерпретация углов полярным преобразованием по формуле output_angle = direction * (input_angle + theta_0).
using CairoMakie
f = Figure()
ax = PolarAxis(f[1, 1], title = "Reoriented Axis", theta_0 = -pi/2, direction = -1)
lines!(ax, range(0, 8pi, length=300), range(0, 10, length=300))
thetalims!(ax, -pi/6, pi/6)
rlims!(ax, 5, 10)
f
Обратите внимание, что по умолчанию перемещения в настройках rmin и thetalimits блокируются. Их можно разблокировать, вызвав функцию autolimits!(ax[, true]), которая также указывает PolarAxis на возможность получения r- и thetalimits из данных, или задав ax.fixrmin[] = false и ax.thetazoomlock[] = false.
Совместимость типов графиков
Не все типы графиков совместимы с полярным преобразованием. Например, изображение (image) не предназначено для отображения на прямоугольнике. heatmap в некоторой степени работает в CairoMakie, но не в GLMakie из-за различий в реализации бэкенда. surface можно использовать вместо image, так как он генерирует треугольную сетку. Чтобы избежать расширения графика surface в z-направлении и тем самым нарушения порядка отрисовки, рекомендуется передавать данные о цвете через атрибут color и использовать матрицу нулей для z-данных. В качестве замены heatmap можно использовать voronoiplot, который генерирует ячейки произвольной формы вокруг заданных точек. Здесь вам придется задать rlims!(ax, rmax) самостоятельно.
using CairoMakie
f = Figure(size = (800, 500))
ax = PolarAxis(f[1, 1], title = "Surface")
rs = 0:10
phis = range(0, 2pi, 37)
cs = [r+cos(4phi) for phi in phis, r in rs]
p = surface!(ax, 0..2pi, 0..10, zeros(size(cs)), color = cs, shading = NoShading, colormap = :coolwarm)
ax.gridz[] = 100
tightlimits!(ax) # графики поверхности включают заполнение по умолчанию
Colorbar(f[2, 1], p, vertical = false, flipaxis = false)
ax = PolarAxis(f[1, 2], title = "Voronoi")
rs = 1:10
phis = range(0, 2pi, 37)[1:36]
cs = [r+cos(4phi) for phi in phis, r in rs]
p = voronoiplot!(ax, phis, rs, cs, show_generators = false, strokewidth = 0)
rlims!(ax, 0.0, 10.5)
Colorbar(f[2, 2], p, vertical = false, flipaxis = false)
f
Обратите внимание, что для того, чтобы увидеть сетку, нужно настроить ее глубину с помощью ax.gridz[] = 100 (большее значение z означает меньшую глубину). Жесткие ограничения для ax.gridz составляют (-10_000, 10_000), а 9000 представляет собой мягкое ограничение, при котором упорядочение компонентов оси может быть неправильным.
Скрытие линий и дополнительных элементов
Для PolarAxis внешнее кольцо, ограничивающее область построения, интерпретируется как линия оси. Работа с ней осуществляется с помощью атрибутов spine....
using CairoMakie
f = Figure(size = (800, 400))
ax1 = PolarAxis(f[1, 1], title = "No spine", spinevisible = false)
scatterlines!(ax1, range(0, 1, length=100), range(0, 10pi, length=100), color = 1:100)
ax2 = PolarAxis(f[1, 2], title = "Modified spine")
ax2.spinecolor[] = :red
ax2.spinestyle[] = :dash
ax2.spinewidth[] = 5
scatterlines!(ax2, range(0, 1, length=100), range(0, 10pi, length=100), color = 1:100)
f
И с помощью атрибутов можно также настроить дополнительные элементы, такие как линии сетки и метки делений.
using CairoMakie
f = Figure(size = (600, 600), backgroundcolor = :black)
ax = PolarAxis(
f[1, 1],
backgroundcolor = :black,
# вспомогательная r-сетка
rminorgridvisible = true, rminorgridcolor = :red,
rminorgridwidth = 1.0, rminorgridstyle = :dash,
# вспомогательная тета-сетка
thetaminorgridvisible = true, thetaminorgridcolor = :lightblue,
thetaminorgridwidth = 1.0, thetaminorgridstyle = :dash,
# основная сетка
rgridwidth = 2, rgridcolor = :red,
thetagridwidth = 2, thetagridcolor = :lightblue,
# r-метки
rticklabelsize = 18, rticklabelcolor = :red,
rticklabelstrokewidth = 1.0, rticklabelstrokecolor = :white,
# тета-метки
thetaticklabelsize = 18, thetaticklabelcolor = :lightblue
)
f
Также можно скрыть созданные линии с помощью hidespines!(ax). Чтобы скрыть метки делений, сетку и (или) вспомогательную сетку, используйте hidedecorations!, hiderdecorations и hidethetadecorations!.
using CairoMakie
fig = Figure()
fullaxis(figpos, title) = PolarAxis(figpos;
title,
thetaminorgridvisible=true,
rminorgridvisible=true,
rticklabelrotation=deg2rad(-90),
rticklabelsize=12,
)
ax1 = fullaxis(fig[1, 1][1, 1], "all decorations")
ax2 = fullaxis(fig[1, 1][1, 2], "hide spine")
hidespines!(ax2)
ax3 = fullaxis(fig[2, 1][1, 1], "hide r decorations")
hiderdecorations!(ax3)
ax4 = fullaxis(fig[2, 1][1, 2], "hide theta decorations")
hidethetadecorations!(ax4)
ax5 = fullaxis(fig[2, 1][1, 3], "hide all decorations")
hidedecorations!(ax5)
fig
Интерактивность
В настоящее время PolarAxis реализует масштабирование, перемещение и сброс настроек. Масштабирование осуществляется с помощью прокрутки, при этом ax.rzoomkey = Keyboard.r ограничивает масштабирование радиальным направлением, а ax.thetazoomkey = Keyboard.t — угловым. Чтобы заблокировать масштабирование в r-направлении, задайте ax.rzoomlock = true и ax.thetazoomlock = true для тета-направления. Кроме того, вы можете отключить масштабирование от изменения только rmin с помощью ax.fixrmin = true и настроить его скорость с помощью ax.zoomspeed = 0.1.
Перемещения осуществляются с помощью перетаскивания при нажатии кнопки мыши. По умолчанию радиальные перемещения используют ax.r_translation_button = Mouse.right, а угловые — ax.theta_translation_button = Mouse.right. Если ax.fixrmin = true, перемещение в r-направлении запрещено. Чтобы отключить одно из этих взаимодействий, задайте false для соответствующей кнопки.
Кроме того, можно поворачивать всю ось с помощью ax.axis_rotation_button = Keyboard.left_control & Mouse.right и сбрасывать представление оси с помощью ax.reset_button = Keyboard.left_control & Mouse.left для соответствующей оси (Axis). С помощью ax.reset_axis_orientation = false можно настроить, следует ли сбрасывать поворот оси.
Обратите внимание, что PolarAxis сейчас не реализует интерфейс взаимодействия, используемый Axis.
Другие примечания
Построение графиков вне PolarAxis
В настоящее время за пределами области PolarAxis есть два полигональных графика, которые обрезают содержимое до нужной области. Чтобы выполнять построение вне отсечения, ограничивающего полярную ось, но при этом в пределах области сцены, нужно преобразовать эти графики в z-диапазон между 9000 и 10_000 или отключить обрезку с помощью атрибута clip.
Для справки: значения z, используемые PolarAxis, равны po.griddepth[] = 8999 для линий сетки, 9000 для многоугольников обрезки, 9001 для линий оси и 9002 для меток делений.
Радиальное смещение
После построения графика со значением rlimits, далеким от 0, у вас будет много пустого пространства в PolarAxis. Рассмотрим пример:
using CairoMakie
fig = Figure()
ax = PolarAxis(fig[1, 1], thetalimits = (0, pi))
lines!(ax, range(0, pi, length=100), 10 .+ sin.(0.3 .* (1:100)))
fig
В данном случае вы можете сместить r-направление, чтобы отображалось больше данных. Поэтому нужно задать ax.radius_at_origin для преобразования радиуса r_out = r_in - radius_at_origin.
using CairoMakie
fig = Figure()
ax = PolarAxis(fig[1, 1], thetalimits = (0, pi), radius_at_origin = 8)
lines!(ax, range(0, pi, length=100), 10 .+ sin.(0.3 .* (1:100)))
fig
using CairoMakie
fig = Figure()
ax = PolarAxis(fig[1, 1], thetalimits = (0, pi), radius_at_origin = -12)
lines!(ax, range(0, pi, length=100), sin.(0.3 .* (1:100)) .- 10)
fig
using CairoMakie
phis = range(pi/4, 9pi/4, length=201)
rs = 1.0 ./ sin.(range(pi/4, 3pi/4, length=51)[1:end-1])
rs = vcat(rs, rs, rs, rs, rs[1])
fig = Figure(size = (900, 300))
ax1 = PolarAxis(fig[1, 1], radius_at_origin = -2, title = "radius_at_origin = -2")
ax2 = PolarAxis(fig[1, 2], radius_at_origin = 0, title = "radius_at_origin = 0")
ax3 = PolarAxis(fig[1, 3], radius_at_origin = 0.5, title = "radius_at_origin = 0.5")
for ax in (ax1, ax2, ax3)
lines!(ax, phis, rs .- 2, color = :red, linewidth = 4)
lines!(ax, phis, rs, color = :black, linewidth = 4)
lines!(ax, phis, rs .+ 0.5, color = :blue, linewidth = 4)
end
fig
Радиальное отсечение
По умолчанию радиусы r_out = r_in - radius_at_origin < 0 обрезаются полярным преобразованием. Эту возможность можно отключить с помощью ax.clip_r = false. Так r_out < 0 пройдет через полярное преобразование как есть, и в результате будет получена координата в точке .
using CairoMakie
fig = Figure(size = (600, 300))
ax1 = PolarAxis(fig[1, 1], radius_at_origin = 0.0, clip_r = true, title = "clip_r = true")
ax2 = PolarAxis(fig[1, 2], radius_at_origin = 0.0, clip_r = false, title = "clip_r = false")
for ax in (ax1, ax2)
lines!(ax, 0..2pi, phi -> cos(2phi) - 0.5, color = :red, linewidth = 4)
lines!(ax, 0..2pi, phi -> sin(2phi), color = :black, linewidth = 4)
end
fig
Атрибуты
MarkdownAST.Heading(3)
Defaults to Inside()
The alignment of the scene in its suggested bounding box.
MarkdownAST.Heading(3)
Defaults to Keyboard.left_control & Mouse.right
Sets the button for rotating the PolarAxis as a whole. This replaces theta translation when triggered and must include a mouse button.
MarkdownAST.Heading(3)
Defaults to inherit(scene, :backgroundcolor, :white)
The background color of the axis.
MarkdownAST.Heading(3)
Defaults to true
Controls whether to activate the nonlinear clip feature. Note that this should not be used when the background is ultimately transparent.
MarkdownAST.Heading(3)
Defaults to true
Controls whether r < 0 (after applying radius_at_origin) gets clipped (true) or not (false).
MarkdownAST.Heading(3)
Defaults to automatic
Sets the color of the clip polygon. Mainly for debug purposes.
MarkdownAST.Heading(3)
Defaults to nothing
Global state for the x dimension conversion.
MarkdownAST.Heading(3)
Defaults to nothing
Global state for the y dimension conversion.
MarkdownAST.Heading(3)
Defaults to 1
The direction of rotation. Can be -1 (clockwise) or 1 (counterclockwise).
MarkdownAST.Heading(3)
Defaults to true
Controls whether rmin remains fixed during zooming and translation. (The latter will be turned off by setting this to true.)
MarkdownAST.Heading(3)
Defaults to -100
Sets the z value of grid lines. To place the grid above plots set this to a value between 1 and 8999.
MarkdownAST.Heading(3)
Defaults to :center
The horizontal alignment of the scene in its suggested bounding box.
MarkdownAST.Heading(3)
Defaults to nothing
The height setting of the scene.
MarkdownAST.Heading(3)
Defaults to true
Sets whether shown theta ticks get normalized to a -2pi to 2pi range. If not, the limits such as (2pi, 4pi) will be shown as that range.
MarkdownAST.Heading(3)
Defaults to Mouse.right
Sets the mouse button for translating the plot in r-direction.
MarkdownAST.Heading(3)
Defaults to automatic
Sets the radius at the origin of the PolarAxis such that r_out = r_in - radius_at_origin. Can be set to automatic to match rmin. Note that this will affect the shape of plotted objects.
MarkdownAST.Heading(3)
Defaults to (0.05, 0.05)
The relative margins added to the autolimits in r direction.
MarkdownAST.Heading(3)
Defaults to false
Sets whether the axis orientation (changed with the axis_rotation_button) gets reset when resetting the axis. If set to false only the limits will reset.
MarkdownAST.Heading(3)
Defaults to Keyboard.left_control & Mouse.left
Sets the button or button combination for resetting the axis view. (This should be compatible with ispressed.)
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xgridcolor), (:black, 0.5))
The color of the r grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xgridstyle), nothing)
The linestyle of the r grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xgridvisible), true)
Controls if the r grid is visible.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xgridwidth), 1)
The linewidth of the r grid.
MarkdownAST.Heading(3)
Defaults to (:origin, nothing)
The radial limits of the PolarAxis.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xminorgridcolor), (:black, 0.2))
The color of the r minor grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xminorgridstyle), nothing)
The linestyle of the r minor grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xminorgridvisible), false)
Controls if the r minor grid is visible.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xminorgridwidth), 1)
The linewidth of the r minor grid.
MarkdownAST.Heading(3)
Defaults to IntervalsBetween(2)
The specifier for the minor r ticks.
MarkdownAST.Heading(3)
Defaults to automatic
The angle in radians along which the r ticks are printed.
MarkdownAST.Heading(3)
Defaults to Makie.automatic
The formatter for the r ticks
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xticklabelcolor), inherit(scene, :textcolor, :black))
The color of the r tick labels.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xticklabelfont), inherit(scene, :font, Makie.defaultfont()))
The font of the r tick labels.
MarkdownAST.Heading(3)
Defaults to 4.0
Padding of the r ticks label.
MarkdownAST.Heading(3)
Defaults to automatic
Sets the rotation of r tick labels.
Options:
-
:radialrotates labels based on the angle they appear at -
:horizontalkeeps labels at a horizontal orientation -
:alignedrotates labels based on the angle they appear at but keeps them up-right and close to horizontal -
automaticuses:horizontalwhen theta limits span >1.9pi and:alignedotherwise -
::Realsets the label rotation to a specific value
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yticklabelsize), inherit(scene, :fontsize, 16))
The fontsize of the r tick labels.
MarkdownAST.Heading(3)
Defaults to automatic
The color of the outline of r ticks. By default this uses the background color.
MarkdownAST.Heading(3)
Defaults to 0.0
The width of the outline of r ticks. Setting this to 0 will remove the outline.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xticklabelsvisible), true)
Controls if the r ticks are visible.
MarkdownAST.Heading(3)
Defaults to LinearTicks(4)
The specifier for the radial (r) ticks, similar to xticks for a normal Axis.
MarkdownAST.Heading(3)
Defaults to Keyboard.r
Sets the key used to restrict zooming to the r-direction. Can be set to true to always restrict zooming or false to disable the interaction.
MarkdownAST.Heading(3)
Defaults to false
Controls whether adjusting the rlimits through interactive zooming is blocked.
MarkdownAST.Heading(3)
Defaults to 90
The density at which curved lines are sampled. (grid lines, spine lines, clip)
MarkdownAST.Heading(3)
Defaults to :black
The color of the spine.
MarkdownAST.Heading(3)
Defaults to nothing
The linestyle of the spine.
MarkdownAST.Heading(3)
Defaults to true
Controls whether the spine is visible.
MarkdownAST.Heading(3)
Defaults to 2
The width of the spine.
MarkdownAST.Heading(3)
Defaults to true
Controls if the parent layout can adjust to this element’s height
MarkdownAST.Heading(3)
Defaults to true
Controls if the parent layout can adjust to this element’s width
MarkdownAST.Heading(3)
Defaults to 0.0
The angular offset for (1, 0) in the PolarAxis. This rotates the axis.
MarkdownAST.Heading(3)
Defaults to true
Controls the argument order of the Polar transform. If theta_as_x = true it is (θ, r), otherwise (r, θ).
MarkdownAST.Heading(3)
Defaults to Mouse.right
Sets the mouse button for translating the plot in theta-direction. Note that this can be the same as radial_translation_button.
MarkdownAST.Heading(3)
Defaults to (0.05, 0.05)
The relative margins added to the autolimits in theta direction.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :ygridcolor), (:black, 0.5))
The color of the theta grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :ygridstyle), nothing)
The linestyle of the theta grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :ygridvisible), true)
Controls if the theta grid is visible.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :ygridwidth), 1)
The linewidth of the theta grid.
MarkdownAST.Heading(3)
Defaults to (0.0, 2pi)
The angle limits of the PolarAxis. (0.0, 2pi) results a full circle. (nothing, nothing) results in limits picked based on plot limits.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yminorgridcolor), (:black, 0.2))
The color of the theta minor grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yminorgridstyle), nothing)
The linestyle of the theta minor grid.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yminorgridvisible), false)
Controls if the theta minor grid is visible.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yminorgridwidth), 1)
The linewidth of the theta minor grid.
MarkdownAST.Heading(3)
Defaults to IntervalsBetween(2)
The specifier for the minor theta ticks.
MarkdownAST.Heading(3)
Defaults to Makie.automatic
The formatter for the theta ticks.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yticklabelcolor), inherit(scene, :textcolor, :black))
The color of the theta tick labels.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yticklabelfont), inherit(scene, :font, Makie.defaultfont()))
The font of the theta tick labels.
MarkdownAST.Heading(3)
Defaults to 4.0
Padding of the theta ticks label.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :xticklabelsize), inherit(scene, :fontsize, 16))
The fontsize of the theta tick labels.
MarkdownAST.Heading(3)
Defaults to automatic
The color of the outline of theta ticks. By default this uses the background color.
MarkdownAST.Heading(3)
Defaults to 0.0
The width of the outline of theta ticks. Setting this to 0 will remove the outline.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :yticklabelsvisible), true)
Controls if the theta ticks are visible.
MarkdownAST.Heading(3)
Defaults to AngularTicks(180 / pi, "°")
The specifier for the angular (theta) ticks, similar to yticks for a normal Axis.
MarkdownAST.Heading(3)
Defaults to Keyboard.t
Sets the key used to restrict zooming to the theta-direction. Can be set to true to always restrict zooming or false to disable the interaction.
MarkdownAST.Heading(3)
Defaults to true
Controls whether adjusting the thetalimits through interactive zooming is blocked.
MarkdownAST.Heading(3)
Defaults to ""
The title of the plot
MarkdownAST.Heading(3)
Defaults to :center
The alignment of the title. Can be any of :center, :left, or :right.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :titlecolor), inherit(scene, :textcolor, :black))
The color of the title.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :titlefont), inherit(scene, :font, Makie.defaultfont()))
The font of the title.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :titlesize), map((x->begin x / 2 end), inherit(scene, :fontsize, 16)))
The gap between the title and the top of the axis
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :titlesize), map((x->begin 1.2x end), inherit(scene, :fontsize, 16)))
The fontsize of the title.
MarkdownAST.Heading(3)
Defaults to inherit(scene, (:Axis, :titlevisible), true)
Controls if the title is visible.
MarkdownAST.Heading(3)
Defaults to :center
The vertical alignment of the scene in its suggested bounding box.
MarkdownAST.Heading(3)
Defaults to nothing
The width setting of the scene.
MarkdownAST.Heading(3)
Defaults to 0.1
Sets the speed of scroll based zooming. Setting this to 0 effectively disables zooming.