首页 > 解决方案 > 如何使用ggplot中的数字变量排序的分组分类变量生成子图?

问题描述

我有一个数据框,其中包含出现在每个文件中text的计数。我想使用 ggplot 生成三个子图,每个 的值一个,在 y 轴上,在 x 轴上频率。我希望根据观察到的每个子图的增加或减少值对每个子图进行排序。我尝试了许多不同的方法来解决这个看似微不足道的问题,但都没有成功。nwordfile_num = 1 or 2 or 3file_numwordnnfile_num

这是dput我的测试数据:

structure(list(file_num = c("1", "1", "1", "1", "2", "2", "2", 
"2", "2", "3", "3", "3", "3", "3"), word = c("test", "quality", 
"page", "limit", "information", "limit", "test", "instruments", 
"quality", "limit", "test", "effective", "page", "system"), n = c(5, 
35, 55, 75, 20, 30, 40, 60, 70, 101, 201, 301, 401, 501)), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -14L), spec = structure(list(
    cols = list(file_num = structure(list(), class = c("collector_character", 
    "collector")), word = structure(list(), class = c("collector_character", 
    "collector")), n = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))

这是我尝试过的:

library(tidytext)
library(stringr)
library(pdftools)
library(dplyr)
library(purrr)
library(ggplot2)
library(forcats)
text %>% group_by(file_num) %>% arrange(file_num, desc(n)) %>%
    ggplot(.,aes(factor(word,levels = unique(word)), n, fill = file_num)) + 
    geom_bar(stat = "identity", position = "dodge") +
    scale_x_discrete("Word") +
    scale_y_continuous("n")  + coord_flip() +
    facet_grid(rows = vars(file_num), scales = "free")

这是使用上述代码在text使用数据创建的dput数据帧上生成的图。它显示了 file_num = 1 的期望结果(word按 的递增值排序n),但不是 file_num = 2 或 3 的结果: 在此处输入图像描述

标签: rggplot2geom-barfactors

解决方案


感谢@Tjebo 为我指明了正确的方向。这是一个基于ggplot. textggplot. _

让我知道是否有办法将修改后的数据框直接导入ggplot

text1 <- text %>% ungroup %>% arrange(file_num, n) %>%
            mutate(order = row_number()) # create variable order 

ggplot(text1,aes(order, n, fill = file_num)) + 
    geom_bar(stat = "identity", show.legend = FALSE) +
    scale_x_continuous(
        breaks = text1$order,
        labels = text1$word,
        expand = c(0,0),
        xlab("Word")) +
    facet_grid(file_num ~ ., scales = "free") +
    coord_flip() 

输出图: 在此处输入图像描述


推荐阅读