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

How to modify x-axis in ggplot with a given vector of labels

我有以下代码:

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

创建以下情节

我想要做的是将 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"))

它产生这个:

正确的做法是什么?

您应该使用 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"))