r - 如何使用ggplot中的数字变量排序的分组分类变量生成子图?
问题描述
我有一个数据框,其中包含出现在每个文件中text
的计数。我想使用 ggplot 生成三个子图,每个 的值一个,在 y 轴上,在 x 轴上频率。我希望根据观察到的每个子图的增加或减少值对每个子图进行排序。我尝试了许多不同的方法来解决这个看似微不足道的问题,但都没有成功。n
word
file_num = 1 or 2 or 3
file_num
word
n
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
数据帧上生成的图。它显示了 file_num = 1 的期望结果(word
按 的递增值排序n
),但不是 file_num = 2 或 3 的结果:
解决方案
感谢@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()
推荐阅读
- android - 同一应用中的 Google RealTime dB 和 Firestore
- azure - 使用 B2C 租户域时,使用 Azure AD B2C 保护的 Azure 函数返回未经授权
- python - 如何在大量日志文件中搜索 Python 中的特定关键字?
- php - 如何在mysql中以Implode形式插入数组值
- php - PHP Snippet - Edge/Firefox 上的 WordPress 问题
- python - 带列表的字母计数器
- mysql - 将 SQL 查询转换为 mysql 查询时出错
- git - 为什么git在远程解析增量之前将对象写入远程
- android - android.arch.lifecycle:extensions:1.1.1 目录
- android - 我有一个错误,这是我的错误:确保首先调用 FirebaseApp.initializeApp(Context)