Cryptic Species
Cryptic Species

Reputation: 43

ggplot2 - how to limit panel and axis?

I want to know how to turn this plot:

plot 1

Into this plot:

plot 2

As you can see the panel and axis on the 2nd plot are limited to the data extent. I made the second graph using design software but want to know the code.

Ive already limited the x and y axis using

xlim and ylim but no difference.

Please see my code below, sorry its so messy, first time using r studio. Thanks!

ggplot() +
  geom_errorbar(data = U1483_Coiling_B_M_Removed_R, mapping = aes(x = `Age (Ma) Linear Age Model`, ymin = `Lower interval*100`, ymax = `Upper interval*100`), width = 0.025, colour = 'grey') +
  geom_line(data = U1483_Coiling_B_M_Removed_R, aes(x = `Age (Ma) Linear Age Model`, y = `Percent Dextral`)) +
  geom_point(data = U1483_Coiling_B_M_Removed_R, aes(x = `Age (Ma) Linear Age Model`, y = `Percent Dextral`), colour = 'red') +
  geom_point(data = U1483_Coiling_B_M_Removed_R, aes(x = `Age (Ma) Linear Age Model`, y = `Lab?`)) +
  theme(axis.text.x=element_text(angle=90, size=10, vjust=0.5)) +
  theme(axis.text.y=element_text(angle=90, size=10, vjust=0.5)) +
  theme_classic() +
  theme(panel.background = element_rect(colour = 'black', size = 1)) +
  xlim(0, 2.85) +
  ylim(0, 100)

Upvotes: 4

Views: 952

Answers (1)

Dan
Dan

Reputation: 12084

You can use expand when specifying axis scales, like so:

# Load library
library(ggplot2)

# Set RNG
set.seed(0)

# Create dummy data
df <- data.frame(x = seq(0, 3, by = 0.1))
df$y <- 100 - abs(rnorm(nrow(df), 0, 10))

# Plot results
# Original
ggplot(df, aes(x, y)) + 
  geom_line() +
  geom_point(colour = "#FF3300", size = 5) 

# With expand
ggplot(df, aes(x, y)) + 
  geom_line() +
  geom_point(colour = "#FF3300", size = 5) +
  scale_y_continuous(expand = c(0, 0))

Upvotes: 2

Related Questions