在-轴ggplot中对几个因子变量进行排序 [英] Ordering Several factor variables in -axis ggplot

查看:82
本文介绍了在-轴ggplot中对几个因子变量进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了几个有关x轴标记顺序的问题,但仍然没有一个可以解决我的问题.我正在尝试绘制一个图表,其中包含两个不同的10个变量.我的变量是一个因数,其结构是这样的:

I've seen several questions about the order of x-axis marks but still, none of them could solve my problem. I'm trying to do a plot that counts 10 variables in two different. My variables are a factor , and the structure is something like that:

crime_1   crime_2 ......  crime_10
Yes         No               Yes
Yes         Yes              No
No          Yes              No

我使用了以下代码:

new_data %>%
  pivot_longer(cols = starts_with("crime")) %>%
    filter(value != 0) %>%
  unite(crime,name, value) %>%
  ggplot(aes(x = crime )) +
    geom_bar(aes(fill = wave), position = position_dodge2(preserve = "single"))+ theme(axis.text.x=element_text(angle=90,hjust=1))+ggtitle("Crime")

输出为NOT Crime_1,Crime_2,.......,Crime_10,它是Crime_1,Crime_10,Crime_2,,,,,.我用过 scale_x_discrete(drop = FALSE)和fct_inorder().

The output is NOT crime_1, crime_2, ......., crime_10, and it is crime_1, crime_10, crime_2, ,,,, . I have used scale_x_discrete(drop = FALSE ), and fct_inorder().

我需要根据顺序进行变量设置.谢谢

I need to make the variables based on the order. Thank you

推荐答案

您已经注意到,x轴上的顺序是字母顺序,而不是数字顺序.这是一种解决方法.

As you noted, the order on the x-axis is in alphabetic order, and not numerical order. Here is one approach to fix that.

使用 stringr 包中的 str_sort 函数,您可以执行以下操作:

Using the str_sort function from the stringr package you can take:

vec <- c("sb_1_x", "sb_10_b", "sb_11_c", "sb_2_y")
vec

[1] "sb_1_x"  "sb_10_b" "sb_11_c" "sb_2_y"

并按中间数字排序:

str_sort(vec, numeric = T)

[1] "sb_1_x"  "sb_2_y"  "sb_10_b" "sb_11_c"

在这种情况下,请确保 sb 是一个因子,然后使用 str_sort 设置因子的水平.我还重命名了x轴标签(可以替换为所需的标签).全部放在一起:

In this case, make sure sb is a factor, and use str_sort to set the factor's levels. I also renamed the x-axis label (you can replace with what you need). Putting it all together:

library(tidyverse)
library(ggplot2)
library(stringr)

df %>%
  pivot_longer(cols = starts_with("sb")) %>%
  filter(value != 0) %>%
  unite(sb, name, value) %>%
  ggplot(aes(x = factor(sb, levels = str_sort(unique(sb), numeric = TRUE)))) +
    geom_bar(aes(fill = wave), position = position_dodge2(preserve = "single")) +
    xlab("x-axis label")

情节

这篇关于在-轴ggplot中对几个因子变量进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆