如何在ggplot中重新排序以数字+字符串作为刻度标签的数字?

huangapple go评论81阅读模式
英文:

How to reorder numbers+string used as ticker in ggplot?

问题

我尝试重新排列我的x轴刻度,使它们按照如下方式排列:DQQ1、DQQ2、DQQ3等等,但我找不到解决方案。有人对如何处理这个问题有什么想法吗?谢谢。

我的代码:

d %>%
  filter(ISO3 == "SLE") %>%
  select(starts_with("DQQ"), YEAR_WAVE) %>%
  pivot_longer(cols = starts_with("DQQ"), names_to = "DQQ", values_to = "Value") %>%
  filter(Value == 1) %>%
  mutate(DQQ = as.factor(DQQ)) %>%
  ggplot(aes(fct_relevel(DQQ, sort), fill = as.factor(YEAR_WAVE))) +
  geom_bar(position = "dodge") +
  labs(
    title = "DQQ YES Answer Counts",
    subtitle = "Counts of 'Yes' answers to DQQ indicators for Sierra Leone",
    fill = "Year",
  ) +
  scale_y_continuous(expand = expansion(add = c(0, 200))) +
  theme(
    panel.background = element_rect(fill = "white"),
    panel.border = element_blank(),
    axis.line.x = element_blank(),
    axis.line.y = element_blank(),
    plot.margin = unit(c(0, .5, 0, 0), "cm"),
    axis.ticks.length = unit(0, "cm"),
    #aspect.ratio = 0.5,
    legend.position = c(0.75, .95),
    legend.justification = c("right", "top"),
    legend.box.just = "right",
    legend.margin = margin(6, 6, 6, 6),
    axis.title.y = element_text(color = "#993333", size = 14, face = "bold"),
    axis.title.x = element_blank(),
    axis.text.x = element_text(face="bold", color="#993333", size = 12, angle=90, hjust = 0.1, vjust = 0.5)
  )

[![enter image description here][1]][1]


图片链接:https://i.stack.imgur.com/i6jfK.jpg

<details>
<summary>英文:</summary>

I have tried to reorder my x axis tickers so they follow like: DQQ1, DQQ2, DQQ3 and etc. but I couldn&#39;t find the solution. Does anybody have an idea about how to deal with this problem. Thank you. 

my code: 

    d %&gt;%
      filter(ISO3 == &quot;SLE&quot;) %&gt;%
      select(starts_with(&quot;DQQ&quot;), YEAR_WAVE) %&gt;%
      pivot_longer(cols = starts_with(&quot;DQQ&quot;), names_to = &quot;DQQ&quot;, values_to = &quot;Value&quot;) %&gt;%
      filter(Value == 1) %&gt;%
      mutate(DQQ = as.factor(DQQ)) %&gt;%
      ggplot(aes(fct_relevel(DQQ, sort), fill = as.factor(YEAR_WAVE))) +
      geom_bar(position = &quot;dodge&quot;) +
      labs(
        title = &quot;DQQ YES Answer Counts&quot;,
        subtitle = &quot;Counts of &#39;Yes&#39; answers to DQQ indicators for Sierra Leone&quot;,
        fill = &quot;Year&quot;,
           ) +
      scale_y_continuous(expand = expansion(add = c(0, 200))) +
      theme(
        panel.background = element_rect(fill = &quot;white&quot;),
        panel.border = element_blank(),
        axis.line.x = element_blank(),
        axis.line.y = element_blank(),
        plot.margin = unit(c(0, .5, 0, 0), &quot;cm&quot;),
        axis.ticks.length = unit(0, &quot;cm&quot;),
        #aspect.ratio = 0.5,
        legend.position = c(0.75, .95),
        legend.justification = c(&quot;right&quot;, &quot;top&quot;),
        legend.box.just = &quot;right&quot;,
        legend.margin = margin(6, 6, 6, 6),
        axis.title.y = element_text(color = &quot;#993333&quot;, size = 14, face = &quot;bold&quot;),
        axis.title.x = element_blank(),
        axis.text.x = element_text(face=&quot;bold&quot;, color=&quot;#993333&quot;, size = 12, angle=90, hjust = 0.1, vjust = 0.5)
      )
[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/i6jfK.jpg

</details>


# 答案1
**得分**: 1

你可以通过以下方式实现:
1. 使用 `stringr::str_extract()` 提取相关数字。
2. 使用 `forcats::fct_reorder()` 根据排名重新排序变量。

这里是一个示例:

``` r
library(tibble) # for tribble()
library(dplyr)
library(stringr) # for str_extract()
library(forcats) # for fct_reorder()
library(ggplot2)

dummy <- 
  tribble(
    ~id,       ~value,
    "DQQ13",    10,
    "DQQ10",    8,
    "DQQ05",    13,
    "DQQ22_03", 7,
    "DQQ22_01", 11
  )

head(dummy)
#> # A tibble: 5 × 2
#>   id       value
#>   <chr>    <dbl>
#> 1 DQQ13       10
#> 2 DQQ10        8
#> 3 DQQ05       13
#> 4 DQQ22_03     7
#> 5 DQQ22_01    11

# 转换为有序因子
dummy <- mutate(dummy, id = ordered(id))

# 通过从字符串中提取第一个数字来创建数字排名变量
dummy <- mutate(dummy, 
                rank = str_extract(id, "\\d+") |>
                  as.numeric())

# 使用排名变量重新排序
dummy <- mutate(dummy, fct_reorder(id, rank))

# 检查是否成功
levels(dummy[["id"]])
#> [1] "DQQ05"    "DQQ10"    "DQQ13"    "DQQ22_01" "DQQ22_03"

# 绘图
ggplot(dummy, aes(x = id, y = value)) + 
  geom_col(fill = "cyan3", col = "black") +
  theme_minimal()

如何在ggplot中重新排序以数字+字符串作为刻度标签的数字?

创建于2023-06-01,使用 reprex v2.0.2

英文:

You can do this by:

  1. Using stringr::str_extract() to extract the relevant numbers.
  2. Using forcats::fct_reorder() to reorder your variable according to its rank

Here is a toy example:

library(tibble) # for tribble()
library(dplyr)
library(stringr) # for str_extract()
library(forcats) # for fct_reorder()
library(ggplot2)

dummy &lt;- 
  tribble(
    ~id,       ~value,
    &quot;DQQ13&quot;,    10,
    &quot;DQQ10&quot;,    8,
    &quot;DQQ05&quot;,    13,
    &quot;DQQ22_03&quot;, 7,
    &quot;DQQ22_01&quot;, 11
  )

head(dummy)
#&gt; # A tibble: 5 &#215; 2
#&gt;   id       value
#&gt;   &lt;chr&gt;    &lt;dbl&gt;
#&gt; 1 DQQ13       10
#&gt; 2 DQQ10        8
#&gt; 3 DQQ05       13
#&gt; 4 DQQ22_03     7
#&gt; 5 DQQ22_01    11

# convert to ordered factor
dummy &lt;- mutate(dummy, id = ordered(id))

# make numerical rank variable by extracting first number
# from string
dummy &lt;- mutate(dummy, 
                rank = str_extract(id, &quot;\\d+&quot;) |&gt; 
                  as.numeric())

# reorder using ranking variabel
dummy &lt;- mutate(dummy, fct_reorder(id, rank))

# Check it&#39;s worked
levels(dummy[[&quot;id&quot;]])
#&gt; [1] &quot;DQQ05&quot;    &quot;DQQ10&quot;    &quot;DQQ13&quot;    &quot;DQQ22_01&quot; &quot;DQQ22_03&quot;

# Plot
ggplot(dummy, aes(x = id, y = value)) + 
  geom_col(fill = &quot;cyan3&quot;, col = &quot;black&quot;) +
  theme_minimal()

如何在ggplot中重新排序以数字+字符串作为刻度标签的数字?<!-- -->

<sup>Created on 2023-06-01 with reprex v2.0.2</sup>

答案2

得分: 0

默认情况下,因子会按照字符串排序。为了得到你想要的结果,你需要按照数字(而不是字符串)对其进行排序。你可以使用下面的代码重新排序 x 轴,并将其传递给 aes():

d <- c("DQQ1", "DQQ10", "DQQ17", "DQQ2")
factor(d, levels = d[order(as.numeric(str_extract(d, "\\d+")))])
英文:

By default the factor orders based on the string. In order to give the result that you want, you have to order it by the number (not the string). You can reorder of the x axis with below code and give to the x axis on aes():

d &lt;- c(&quot;DQQ1&quot;, &quot;DQQ10&quot;, &quot;DQQ17&quot;, &quot;DQQ2&quot;)
factor(d, levels = d[order(as.numeric(str_extract(d, &quot;\\d+&quot;)))])

huangapple
  • 本文由 发表于 2023年6月1日 21:10:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定