当y轴在ggplot2中变为负值时,如何在y = 0处添加刻度线?

时间:2017-01-30 23:13:36

标签: r ggplot2

y=0不在y轴的底部时,有没有办法在y=0添加刻度线?在这个粗略的例子中,y轴的范围从 - $ 20,000到$ 20,000,我在geom_hline添加了y=0,并删除了轴刻度。但是,我无法弄清楚如何在图表中间的y=0处添加细微的刻度:

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")

关于删除刻度线和沿 x轴和y轴间距刻度线的问题,有一些令人讨厌的问题,但我无法找到问题的答案。谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用annotate或与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