如何使用给定的标签向量修改ggplot中的x轴

时间:2018-03-19 01:27:27

标签: r ggplot2 tidyverse

我有以下代码:

library(ggplot2)
ggplot(cars, aes(x = speed, y = dist)) + 
  geom_line() 

创建以下情节

enter image description here

我想要做的是将x轴(speed)值5,10,15,20,25替换为以下向量:c("-5000", "-2500", "FOO", "2500", "5000")

但为什么会失败?

 ggplot(cars, aes(x = speed, y = dist)) + geom_line() + 
    scale_x_discrete(labels = c("-5000", "-2500", "TSS", "2500", "5000"))

它产生了这个:

enter image description here

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:5)

您应该使用scale_x_continuous(),因为速度是一个连续变量。您还需要指定中断,即在哪里放置刻度。

ggplot(cars, aes(x = speed, y = dist)) + geom_line() +
  scale_x_continuous(breaks = c(5, 10, 15, 20, 25), 
                     labels = c("-5000", "-2500", "TSS", "2500", "5000"))

enter image description here

相关问题