【问题标题】:Only show one part of interacting x variable in x-axis labels in ggplot在ggplot的x轴标签中只显示交互x变量的一部分
【发布时间】:2018-04-26 15:54:46
【问题描述】:

我在 ggplot 的 x 轴上绘制交互变量,例如如下所示。由于我使用填充颜色来指示其中一个值(此处为 variable),因此我只希望我的 x 轴标签显示另一个变量(此处为 study_day)。我无法指定手动比例 (scale_x_discrete(labels = c('1', '1', '1', '2', '2', '2')),因为我的 study_day 值可能在每个方面都不同,如本例所示。如何指示只用study_day 标记x 轴?

set.seed(1)
df <- data.frame(variable = rep(c('A', 'B', 'C'), 8),
                 study_day = rep(c('1', '2'), 12),
                 ID = rep(c('W', 'X', 'Y', 'Z'), 6),
                 value = rnorm(24))

ggplot(df, aes(interaction(variable, study_day), value))+
  geom_point(shape = 21, aes(fill = variable))+
  facet_wrap(~ID, scales = 'free')

【问题讨论】:

  • 使用scale_x_discrete。你可以给它一个labeler函数,比如labels = function(x) stringr::str_extract(x, "\\d+"),它将从“A.1”、“B.1”等中提取出数字
  • 使用闪避代替交互变量怎么样?所以将study_day 放在x 轴上,然后在geom_point 中使用position = position_dodge(width = .5)(任意宽度)。

标签: r ggplot2 axis-labels


【解决方案1】:

您可以编写一个make_labels() 函数,从 ggplot2 生成的标签中提取学习日:

library(stringr)

make_labels <- function(labels) {
  result <- str_split(labels, "\\.")
  unlist(lapply(result, function(x) x[2]))
}

set.seed(1)
df <- data.frame(variable = rep(c('A', 'B', 'C'), 8),
                 study_day = rep(c('1', '2'), 12),
                 ID = rep(c('W', 'X', 'Y', 'Z'), 6),
                 value = rnorm(24))

ggplot(df, aes(interaction(variable, study_day), value))+
  geom_point(shape = 21, aes(fill = variable))+
  facet_wrap(~ID, scales = 'free') +
  scale_x_discrete(labels = make_labels, name = "study day")

【讨论】:

    猜你喜欢
    • 2020-10-24
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多