简体   繁体   English

在ggplot2中粘贴标签的函数

[英]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)

在此处输入图片说明

But it did not work. 但这没有用。 Why? 为什么? (main question) (主要问题)

I want to search for solutions that make labels = c("'q1' = 1", ...) works. 我想搜索使labels = c("'q1' = 1", ...)起作用的解决方案。

Beside paste function I know two alternatives. 除了paste功能,我知道两种选择。

Using list: 使用清单:
 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))

在此处输入图片说明

why not giving a named vector? 为什么不给出命名向量?

labels <- parse_number(as.character(daata$q))
names(labels) <- as.character(daata$q)

p1 <- ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
  geom_col() 

p2 <- p1  + scale_x_discrete(labels = labels)
cowplot::plot_grid(p1, p2, nrow = 1)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM