在下面的图中,我想通过paste0
函数重命名x轴。
daata <- data.frame(
q = paste0("q",1:20),
value = runif(n = 20, 2, 10))
ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
geom_col()
所以我使用了以下代码:
q = paste0("q",1:20)
labels <- paste0("'", q,"'" , " = ", 1:20) %>% noquote()
# Or
labels <- noquote(paste0("'", q,"'" , " = ", 1:20))
ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
geom_col() +
scale_x_discrete(labels = labels)
我想搜索使labels = c("'q1' = 1", ...)
有效的解决方案。
paste
函数旁边,我知道两种选择。labels = sapply(1:20, list)
names(labels) <- daata$q
ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
geom_col() +
scale_x_discrete(labels = labels)
使用功能:
ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
geom_col() +
scale_x_discrete(labels = function(i){gsub("q", "", i)})
我也很想知道其他解决方案。
答案 0 :(得分:0)
这样的事情怎么样?在data =
步骤中提取问题编号,并将其用于轴:
daata <- data.frame(
q = paste0("q",1:20),
value = 1:20)
ggplot2::ggplot(data = daata %>% mutate(order = str_remove(q, "q") %>% as.numeric),
aes(x = order, y = value)) +
geom_col() +
scale_x_continuous(breaks = 1:20, minor_breaks = NULL)
编辑:这是提取标签数字部分的替代方法。您将注意到,这保留了通过将x映射到q
所创建的字母顺序。
ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
geom_col() +
scale_x_discrete(labels = function(x) parse_number(x))
答案 1 :(得分:0)