0

I want to recreate the following plot which only shows tick marks on y and x axis at the start and the end of the line. Picture of Plot. I have the following code so far:

elevation_plot <- StradeBianche%>%
  ggplot(aes(x = `Accumulated Distance in Km`))+
  geom_area(aes(y = elevation), fill = "grey")+
  coord_cartesian(ylim = c(100,500))+
  scale_y_continuous(expand = c(0,0), limits = c(0, 500),  labels = label_number(suffix = " m"))+
  scale_x_continuous(expand = c(0,0), breaks = seq(0, 180, 20), labels = label_number(suffix = ".0 km"))+
  theme(panel.grid.minor = element_blank())+
  theme(panel.grid.major = element_blank())+
  theme(panel.background = element_rect(fill = "white"))+
  theme(panel.border = element_blank())+
  theme(axis.title = element_blank())+
  theme(axis.ticks = element_blank())

The result is this:Picture of result. It comes quite close but the ticks are still missing... I can either remove all axis ticks or none. But I can not manage to set only certain axis ticks without removing the x and y values along the axis.

Any help is greatly appreciated!

2 Answers2

0

You could use the pretty_breaks function from the scales library:

ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10))

Where n defines the number of ticks

Check out https://stackoverflow.com/a/31408489/15235792

0

You can immitate ticks behaviour if you place geom_segment()s at the right coordinates and turn off the clipping of the data. The downside is that you cannot place the segment endpoints relative to the first in absolute units, so you'd have to fiddle with the offset and text margins. Example below:

library(ggplot2)

xlim <- c(1, 5)
ylim <- c(4, 8)
offset <- 0.05

seg <- data.frame(
  x    = xlim[c(1,2,1,1)],
  xend = xlim[c(1,2,1,1)] - c(0, 0, offset, offset),
  y    = ylim[c(1,1,2,1)],
  yend = ylim[c(1,1,2,1)] - c(offset, offset, 0, 0)
)

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point(aes(colour = Species)) +
  geom_segment(data = seg, aes(x = x, y = y, xend = xend, yend = yend)) +
  coord_cartesian(clip = "off",
                  xlim = xlim,
                  ylim = ylim, 
                  expand = FALSE) +
  theme(axis.ticks = element_blank(),
        axis.line = element_line(),
        axis.text.x = element_text(margin = margin(t = 8)),
        axis.text.y = element_text(margin = margin(r = 8)))

Created on 2021-03-25 by the reprex package (v1.0.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63