awunderground
awunderground

Reputation: 134

How can I add tick marks at y=0 when y-axis goes negative in ggplot2?

Is there a way to add tick marks at y=0 when y=0 isn't at the bottom of the y-axis? In this crude example, the y-axis ranges from -$20,000 to $20,000, I added a geom_hline at y=0, and removed the axis ticks. However, I can't figure out how to add subtle ticks on the line at y=0 which is in the middle of the chart:

diamonds %>%
  mutate(price = ifelse(cut == "Very Good", price * -1, price)) %>%
  ggplot(aes(carat, price)) +
  geom_point() +
  geom_abline(yintercept = 0) +
  theme(axis.ticks.length = unit(0, "points"),
        panel.background = element_rect(fill = "white"),
        axis.line.y = element_line(color = "black")) +
  labs(title = "Diamonds")

There's an obnoxious number of questions about removing tick marks and spacing tick marks along the x- and y- axes, but I could not find an answer to my question. Thank you!

Upvotes: 2

Views: 1651

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23109

You can try this with annotate or equivalently with geom='segment'

x.axis.labels <- seq(0,5,0.25) # positions of the subtle ticks
diamonds %>%
  mutate(price = ifelse(cut == "Very Good", price * -1, price)) %>%
  ggplot(aes(carat, price)) +
  geom_point() +
  geom_hline(yintercept = 0) +
  theme(axis.ticks.length = unit(0, "points"),
        panel.background = element_rect(fill = "white"),
        axis.line.y = element_line(color = "black")) +
  labs(title = "Diamonds") +
  annotate(geom='point', x=x.axis.labels, y = 0, ymin=-10, ymax=10) +
  annotate(geom='text', x=x.axis.labels, y = -200, label=x.axis.labels, vjust=1)

enter image description here

Upvotes: 4

Related Questions