在ggplot2中粘贴标签的功能

时间:2019-07-01 21:05:45

标签: r ggplot2

在下面的图中,我想通过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)

enter image description here

但是没有用。为什么? (主要问题)

我想搜索使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)})

我也很想知道其他解决方案。

2 个答案:

答案 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)

enter image description here

编辑:这是提取标签数字部分的替代方法。您将注意到,这保留了通过将x映射到q所创建的字母顺序。

ggplot2::ggplot(data = daata, aes(x = q, y = value)) +
  geom_col() + 
  scale_x_discrete(labels = function(x) parse_number(x))

enter image description here

答案 1 :(得分:0)

为什么不给出命名载体?

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)

enter image description here