Jmac
Jmac

Reputation: 243

Can you remove the space between axis and data in ggplot with discrete scales

Is it possible to reduce the space between the axis and data in a ggplot (point) with a discrete scale. I've seen a lot of ways of doing this with discrete scales but can't seem to get it to work in this situation (discrete scale with 1 value on the axis).

ggplot with discrete axis - too much space between axis and text

I have tried converting to numeric and using expand(c(0,0) based on this response. It works when applied to the x axis but not the y-axis (possibly because there is only one break on the y-axis?)

library(tidyverse)

df <- tibble(Site = rep("A", 4), 
             Basin = rep("B1", 4), 
             Variable = c("V1", "V2", "V3", "V4"), 
             cls = c("up", "down", "ns", "up"))

#basic plot (output above)
p <- ggplot(df , aes(x=Variable, y=Site)) +
  geom_point(size=3, aes(color=cls, shape=cls, fill=cls)) + 
  facet_grid(Basin~., scales="free", space="free")
p

#attempting to convert discrete scale to continuous and apply limits to axis
p2 <- ggplot(df , aes(x=Variable, y=c(as.numeric(factor(df$Site)))) +
  geom_point(size=3, aes(color=cls, shape=cls, fill=cls)) + 
  scale_y_continuous(limits=c(0.95,1.05),breaks=1,labels=levels(factor(df$Site)), expand=c(0,0))+
  facet_grid(Basin ~ ., scales="free", space="free")

#I have also tried using 
  scale_y_discrete(expand=expand_scale(mult = c(0.01, .01)))



#when same method is applied to the axis it seems to work - is this because there is more than 1 break/variable
 p3 <- ggplot(df , aes(x=as.numeric(df$Variable), y=as.numeric(factor(df$Site)))) +
  geom_point(size=3, aes(color=cls, shape=cls, fill=cls)) + 
  scale_x_continuous(limits=c(0.95,4.05),breaks=seq(1:length(unique(df$Variable))),labels=levels(factor(df$Variable)),
                      expand=c(0,0))+
  facet_grid(Basin~., scales="free", space="free")

Upvotes: 3

Views: 2387

Answers (1)

yake84
yake84

Reputation: 3236

You can use expand_scale() to adjust the limits of the axis. The mult argument will multiply the min and max of the current scale by the percentage you give it. mult = c(0.2, 1) means reduce the distance to the bottom to 20% of it's current distance and keep the distance to the top at the original distance.

ggplot(df, aes(x = Variable, y = Site)) +
  geom_point(aes(color = cls, shape = cls, fill = cls), size = 3) +
  facet_grid(Basin ~ ., scales = "free", space = "free") +
  scale_y_discrete(expand = expand_scale(mult = c(0.2, 1)))

enter image description here

Upvotes: 3

Related Questions