如何在ggplot中生成按数字变量排序的分组分类变量的子图?

问题描述 投票:0回答:1

我有一个数据框 text 有数 nword 出现在每个文件中 file_num = 1 or 2 or 3. 我想用ggplot生成三个子图,每个子图对应于 file_num,与 word 在y轴上,频率 n 在x轴上。我想让每个子图按照X轴上的 n 观察到的每个 file_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 数据。 它显示了预期的结果(word 的值越大,排序越高。n),但对file_num = 1,但对file_num = 2或3则不适用。enter image description here

r ggplot2 geom-bar factors
1个回答
0
投票

你可以简单地用以下方法实现 "按面排序"。ggcharts 包,在你的数据上使用以下代码。

library(ggcharts)
bar_chart(data = text, x = word, y = n, 
  fill = file_num,
  facet = file_num,
  horizontal = TRUE
)

这将产生以下的图表。

enter image description here

请告诉我,这是否是你想要的。

更新。

这个对象是由 bar_chart 是一类 ggplot,如下图所示。

class(chart)
[1] "gg"     "ggplot"

这意味着,我们可以使用 ggplot2 函数来改变图形,例如。

chart + 
  guides(fill=FALSE) +      ## remove legend 
  ggtitle("My new title") + ## add title
  theme_linedraw() +
  theme(strip.background = element_rect(colour = "red", size = 2))

产生以下图片(仅作说明) 。

enter image description here


1
投票

感谢@Tjebo给我指出了正确的方向。这里有一个工作解决方案,它是基于 ggplot. 它确实需要一个人保存修改后的数据框架。text 用前 ggplot.

让我知道是否有办法直接将修改后的数据框架管入到 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() 

输出图。enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.