I would like the flip the x and y coordinates of the following plot
library(ggplot2)
ggplot(data = iris) +
geom_dotplot(aes(y = Sepal.Length, x = Species), binaxis = "y")

First, I tried to change all x and y arguments.
ggplot(data = iris) +
geom_dotplot(aes(x = Sepal.Length, y = Species), binaxis = "x")

The dots start at the bottom instead of at the corresponding species level (y-axis).
Another option is the use coord_flip().
ggplot(data = iris) +
geom_dotplot(aes(y = Sepal.Length, x = Species), binaxis = "y") +
coord_flip()

This works but the point size or spacing between y-axis categories is now not automatically adjusted.
Is there another way to do this correctly? Is there a good reason why the second code block does not work?
The coord_flip option is fine, but you would need to reduce the default dotsize or increase the plot dimensions to get these to fit without overlap.
ggplot(data = iris) +
geom_dotplot(aes(y = Sepal.Length, x = Species), binaxis = "y",
dotsize = 0.4, stackratio = 1.5) +
coord_flip() +
theme_gray(base_size = 18)

Another option is to reduce the binwidth so that the counts per bin is smaller:
ggplot(data = iris) +
geom_dotplot(aes(y = Sepal.Length, x = Species), binaxis = "y",
dotsize = 0.8, stackratio = 1.3, binwidth = 0.1) +
coord_flip() +
theme_gray(base_size = 18)

It's not the case that the spacing is automatically adjusted in the first plot and not when you use coord_flip(). It's just the default dimensions of the first plot happen to be wide enough to correctly handle the spacing in this case.
If you save the first plot with different dimensions e.g. ggsave("./tmp.png", width = 4, height = 8), you will see that you face the same issue with overlap.
Your final plot has three dot density plots stacked on top of each other. This means we need to make it taller than it is wide:
ggplot(data = iris) +
geom_dotplot(aes(y = Sepal.Length, x = Species), binaxis = "y") +
coord_flip()
ggsave("./tmp.png", width = 4, height = 6)

Rather than playing around with the width and height of these plots, I think you should use facets instead. In the above plot, the y-axis is Species, but also on the y-axis is the height of the dotted bars, i.e. density. To me the following is much more interpretable:
ggplot(data = iris) +
geom_dotplot(aes(x = Sepal.Length, fill = Species)) +
facet_wrap(~Species, ncol = 1) +
theme(legend.position = "none")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With