[英]paste function for labeling in ggplot2
In the following plot, I want to rename x-axis by paste0
function. 在下图中,我想通过
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()
so I used the following code: 所以我用下面的代码:
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)
I want to search for solutions that make labels = c("'q1' = 1", ...)
works. 我想搜索使
labels = c("'q1' = 1", ...)
起作用的解决方案。
paste
function I know two alternatives. 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)
Using function:
ggplot2::ggplot(data = daata, aes(x = q, y = value)) + geom_col() + scale_x_discrete(labels = function(i){gsub("q", "", i)})
I am eager to know other solutions too. 我也很想知道其他解决方案。
How about something like this? 这样的事情怎么样? Extract the question number in the
data =
step, and use that for the axis: 在
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)
Edit: here's an alternative that extracts the numeric part of the label. 编辑:这是提取标签数字部分的替代方法。 As you'll note, this preserves the alphabetical ordering created by mapping x to
q
. 您将注意到,这保留了通过将x映射到
q
创建的字母顺序。
ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
geom_col() +
scale_x_discrete(labels = function(x) parse_number(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.