Ggplot2: Flip Axes and Maintain Aspect Ratio of Data

ggplot2: Flip axes and maintain aspect ratio of data

I agree that the theme solution isn't really a proper one. Here is a solution that does work programatically by calculating the aspect from the actual axes ranges stored in the plot object, but it takes a few lines of code:

ranges <- ggplot_build(p)$layout$panel_ranges[[1]][c('x.range', 'y.range')]
sizes <- sapply(ranges, diff)
aspect <- sizes[1] / sizes[2]

p + coord_flip() + theme(aspect.ratio = aspect)

Sample Image

The solution I would probably use in practice, is to use the horizontal geoms in the ggstance package (although this may not always be feasible).

Note: This will only give the exact correct answer for two continuous scales with an equal multiplicative extend argument (i.e. the default).

edit: In many cases I would recommend using coord_equal combined with the ggstance package instead of this solution.

Flipping and maintaining aspect ratio of a chart in ggplot2

See this answer on the ggplot2 mailing list :

You can only use one coord_*() function on a given ggplot since it
changes the coordinate system after everything else has been done. To
change the aspect ratio, you can use the corresponding argument in the
theming system:

 + coord_flip() + theme(aspect.ratio = 1)

How to fix the aspect ratio in ggplot?

In ggplot the mechanism to preserve the aspect ratio of your plot is to add a coord_fixed() layer to the plot. This will preserve the aspect ratio of the plot itself, regardless of the shape of the actual bounding box.

(I also suggest you use ggsave to save your resulting plot to pdf/png/etc, rather than the pdf(); print(p); dev.off() sequence.)

library(ggplot2)
df <- data.frame(
x = runif(100, 0, 5),
y = runif(100, 0, 5))

ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed()

Sample Image

How do I to fix aspect ratio and apply coord_flip in ggplot2?

Without reproducible data, my best guess would be to pass aspect.ratio through the theme not in coord_fixed(ratio=0.05)

How to fix aspect ratio with linked axes?

You need to add aspect_ratio=1 to the scatter plot (credit to @mikael-Öhman):

using CairoMakie

n = 3000
r = randn(2,3000)
x = @view r[1,:]
y = @view r[2,:]

fig = Figure(resolution = (1000, 1000), font = "sans", fontsize = 20)
ax1 = (Axis(fig[1, 1]))
density!(ax1, y; bins = 20, color = :orange, strokewidth = 1,
strokecolor = :black, label = "20 bins", aspect=1,aspect_ratio=1)

ax3 = Axis(fig[2, 1]; xlabel = "value", ylabel = "counts")
ax4 = Axis(fig[2, 2]; xlabel = "value", ylabel = "counts")
scatter!(ax3, x, y; markersize = 4, color = :black,label="samples")
axislegend(ax3; position = :rt)

density!(ax4, x; label = "default",direction=:y)
rowsize!(fig.layout, 2, Auto(3))
colsize!(fig.layout, 1, Auto(3))
xlims!(ax3,-4,4)
ylims!(ax3,-4,4)
linkxaxes!(ax1, ax3)
linkyaxes!(ax3, ax4)

fig


Related Topics



Leave a reply



Submit