[英]Only show one part of interacting x variable in x-axis labels in ggplot
I am plotting interacting variables on the x-axis of a ggplot, for example as below. 我在ggplot的x轴上绘制交互变量,例如以下所示。 Since I am using a fill color to indicate one of the values (here, variable
), I would only like my x-axis labels to display the other variable (here, study_day
). 由于我使用填充色来指示其中一个值(此处为variable
),因此我只希望x轴标签显示另一个变量(此处为study_day
)。 I can't specify a manual scale ( scale_x_discrete(labels = c('1', '1', '1', '2', '2', '2')
) because my study_day
values may vary in each facet, as in this example. How do I indicate to only label the x-axis with 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')
You can write a make_labels()
function that extracts the study day from the labels ggplot2 generates: 您可以编写一个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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.