英文:
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't find the solution. Does anybody have an idea about how to deal with this problem. Thank you.
my code:
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]
[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()
创建于2023-06-01,使用 reprex v2.0.2
英文:
You can do this by:
- Using
stringr::str_extract()
to extract the relevant numbers. - 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 <-
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
# convert to ordered factor
dummy <- mutate(dummy, id = ordered(id))
# make numerical rank variable by extracting first number
# from string
dummy <- mutate(dummy,
rank = str_extract(id, "\\d+") |>
as.numeric())
# reorder using ranking variabel
dummy <- mutate(dummy, fct_reorder(id, rank))
# Check it's worked
levels(dummy[["id"]])
#> [1] "DQQ05" "DQQ10" "DQQ13" "DQQ22_01" "DQQ22_03"
# Plot
ggplot(dummy, aes(x = id, y = value)) +
geom_col(fill = "cyan3", col = "black") +
theme_minimal()
<!-- -->
<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 <- c("DQQ1", "DQQ10", "DQQ17", "DQQ2")
factor(d, levels = d[order(as.numeric(str_extract(d, "\\d+")))])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论