scale_x_discrete 5 个刻度,3 个标签

scale_x_discrete 5 ticks with 3 labels

我有5个条件:

 labels = c("Baseline","Passenger Drive","Passenger Drive","Remote Drive","Remote Drive")

我想在现有点中间放置一个 "Passenger Drive" 和 "Remote Drive" 的标签。

玩具数据集:

  df <- data.frame(cbind(cbind(condition = c("Baseline","Passenger Drive",
                        "Passenger Drive","Remote Drive","Remote Drive"),
          rt_type = c("none",rep(c("driver_rt","other_rt"),2))),
  rt = c(.4,.6,.5,.7,.62)))

  ggplot(data = df,aes(x = interaction(rt_type,condition), y = rt)) + 
  theme_classic() + 
  geom_line(group = 1, size = 1) +
  geom_point(size = 3) + 
  scale_x_discrete(labels = c("Baseline",
                              "Passenger Drive",
                              "Remote Drive")) +
  labs(x = "Condition by Speaker", y = "Reaction Time (s)",
       linetype = "Responder", shape = "Speaker")

当我尝试 scale_x_continous 时我得到一个错误,因为数据是离散的和分类的。实际的数据集代表了更多的变量,所以我并不是在寻求一种更有效的方法来绘制这些数据。我只想将 5 个分类 x 轴位置的标签转换为 3 个 x 轴标签。 "Passenger Drive" 将在第 2 点和第 3 点之间移动,"Remote Drive" 将在第 4 点和第 5 点之间移动。

解决方法

简单改变

  scale_x_discrete(labels = c("Baseline",
                              "Passenger Drive",
                              "Remote Drive")) +

  scale_x_discrete(labels = df$condition) +

理想

我知道你不是在寻求一种更有效的方法,但我认为应该将一个变量(例如 rt_type)映射到点形状。

ggplot(data = df, aes(x = condition, y = rt, shape = rt_type)) +
  theme_classic() +
  geom_point(size = 3,) +
  scale_x_discrete(labels = c("Baseline",
                              "Passenger Drive",
                              "Remote Drive")) +
  labs(
    x = "Condition by Speaker",
    y = "Reaction Time (s)"
  )

您可以为 x 轴创建虚拟数值变量并使用 scale_x_continuous 而不是 scale_x_discrete

# This replaces interaction(rt_type, condition)
df$intr <- as.numeric(as.factor(interaction(df$rt_type, df$condition)))

# Creating dummy mid point to place labels in the middle
ref_avg <- aggregate(intr ~ condition, df, mean)
df$my_breaks <- ref_avg[match(df$condition, ref_avg$condition), "intr"]

ggplot(data = df,aes(x = intr, y = rt)) + 
  theme_classic() + 
  geom_point(size = 3)  + 
  geom_path(group = 1) + 
  scale_x_continuous(breaks = df$my_breaks, labels = df$condition) + 
  labs(x = "Condition by Speaker", y = "Reaction Time (s)",
       linetype = "Responder", shape = "Speaker")