我正在嘗試創建分組 x 軸標簽以放置在現有 x 軸標簽之上;最近在 StackOverflow 上的瀏覽??推薦 facet_grid 為此目的。但是,我無法為每個方面修改單獨的 x 軸標簽。代表如下:
library(tidyverse)
# make data
scale <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o")
score <- rep(10, 15)
input <- data.frame(scale, score)
input <- t(input)
names(input) <- input[, 1]
input <- data.frame(janitor::row_to_names(input, row_number = 1))
# put it in a dataframe
df <- data.frame(rbind(
input$a, input$b, input$c, input$d,
input$e, input$f, input$g, input$h, input$i,
input$j, input$k, input$l,
input$m, input$n, input$o)) %>%
tibble::rownames_to_column(var = "scale") %>%
rename(scale_score = 2) %>%
mutate(scale_group = c("SCALE1", "SCALE1", "SCALE1", "SCALE1",
"SCALE2", "SCALE2", "SCALE2", "SCALE2", "SCALE2",
"SCALE3", "SCALE3", "SCALE3",
"SCALE4", "SCALE4", "SCALE4"))
df$scale_group = factor(df$scale_group, levels = c("SCALE1", "SCALE2", "SCALE3", "SCALE4"))
df$gp <- c(1,1,1,1,2,2,2,2,2,3,3,3,4,4,4)
# make ggplot labels
labels = c("A", "B", "C", "(D)",
"E", "F", "G", "(H)", "(I)",
"J", "K", "(L)",
"M", "N", "(O)")
# make a ggplot with facet_grid and it looks weird - why do the sub-labels repeat themselves?
df %>%
ggplot(aes(x=interaction(scale, factor(scale_group)), y=as.numeric(scale_score),
label = (scale_group),
group=interaction(scale_group, gp)))
theme_bw()
geom_line(stat="identity")
geom_point(size=2, color="blue")
geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = 9.5, ymax = 10.5),
alpha = 0.015, fill = "darkturquoise")
scale_y_continuous(breaks = (seq(0, 20, by = 1)), limits = c(0,20))
scale_x_discrete(position = "top", labels = unique(labels))
xlab("") ylab("")
ggtitle("I want to see all the letters, not ABC repeating") theme(plot.title = element_text(hjust = 0.5))
facet_grid( ~ scale_group,
scales = "free", space = "free")

我也想要 SCALE1/SCALE2/等。為上述A,B,C等,但是這可能是一個單獨的quesiton。我將不勝感激任何提示或見解。
uj5u.com熱心網友回復:
以下對我有用。首先,labels使用x-axis標簽中的名稱制作矢量。其次,unique從labels = unique(labels).
# make ggplot labels
labels <- c("A", "B", "C", "(D)",
"E", "F", "G", "(H)", "(I)",
"J", "K", "(L)",
"M", "N", "(O)")
names(labels) <- interaction(df$scale, factor(df$scale_group))
df %>%
ggplot(aes(x=interaction(scale, factor(scale_group)), y=as.numeric(scale_score),
label = (scale_group),
group=interaction(scale_group, gp)))
theme_bw()
geom_line(stat="identity")
geom_point(size=2, color="blue")
geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = 9.5, ymax = 10.5),
alpha = 0.015, fill = "darkturquoise")
scale_y_continuous(breaks = (seq(0, 20, by = 1)), limits = c(0,20))
scale_x_discrete(position = "top", labels = labels)
xlab("") ylab("")
ggtitle("I want to see all the letters, not ABC repeating") theme(plot.title = element_text(hjust = 0.5))
facet_grid( ~ scale_group,
scales = "free", space = "free")

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/350045.html
