scale_x_discrete 5个带有3个标签的刻度

时间:2019-05-24 00:19:29

标签: r ggplot2 axis-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")

Interaction

当我尝试使用带有中断的scale_x_continous时,由于数据是离散的和分类的,因此会出现错误。实际的数据集还代表了几个变量,因此,我不要求一种更有效的方式来绘制此数据。我只想将5个类别x轴位置的标签转换为3个x轴标签。 “乘客驱动器”将在第2点和第3点之间移动,而“远程驱动器”将在第4点和第5点之间移动。

2 个答案:

答案 0 :(得分:1)

解决方法

只需更改

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

答案 1 :(得分:1)

您可以为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")

enter image description here