r - 在具有较少级别的因子变量之后对 x 轴进行排序

标签 r ggplot2

我有以下数据框:

structure(list(Substance = c("Cefotaxime", "Cefepim", "Chloramphenicol", 
"Sulfamethoxazole", "Ampicillin", "Ampicillin", "Tetracycline", 
"Cefotaxime", "Trimethoprim", "Cefepim", "Cefepim", "Sulfamethoxazole", 
"Ceftazidime", "Nalidixic acid", "Cefepim", "Ceftazidime", "Ampicillin", 
"Ceftazidime", "Cefotaxime", "Ceftazidime"), Species = c("Cattle", 
"Chicken", "Cattle", "Cattle", "Cattle", "Cattle", "Cattle", 
"Pig", "Cattle", "Cattle", "Horse", "Horse", "Pig", "Cattle", 
"Pig", "Pig", "Cattle", "Cattle", "Pig", "Horse"), gene = c("AmpC", 
"blaCMY-2", "blaSHV-12", "blaCMY-2", "AmpC", "blaCMY-2", "blaCMY-2", 
"AmpC", "blaSHV-12", "blaSHV-12", "blaCTX-M Group 1", "blaCTX-M Group 1", 
"AmpC", "blaSHV-12", "blaCTX-M-15", "blaCTX-M-15", "AmpC", "AmpC", 
"blaCMY-2", "AmpC"), n = c(3, 6, 1, 1, 3, 1, 1, 3, 1, 1, 1, 1, 
3, 1, 1, 1, 1, 1, 1, 1), group = c(8L, 3L, 5L, 9L, 8L, 9L, 9L, 
13L, 5L, 5L, 2L, 2L, 13L, 5L, 16L, 16L, 7L, 7L, 15L, 1L), value = c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-20L), .Names = c("Substance", "Species", "gene", "n", "group", 
"value"))

我有这个情节:

gene_palette <- c("AmpC" = "#b2182b",
              "blaCMY-2" = "#ef8a62",
              "blaCTX-M-15" = "#fddbc7",
              "blaCTX-M Group 1" = "#d1e5f0",
              "blaSHV-12" = "#67a9cf",
              "ESBL" = "#2166ac")

library(ggplot2)

ggplot(test, aes(factor(group), Substance, fill = gene))+
  geom_point(pch = 21, size = 5)+
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))+
  scale_fill_manual(values = gene_palette)+
  theme_classic()

这会产生以下图:

enter image description here

有没有办法对 x 轴上的“组”顺序进行排序,以便每个基因在 x 轴上彼此相邻,按照图例中列出的顺序?这样,每种基因类型的颜色将彼此相邻。

我尝试了所提供的解决方案 here ,但由于“gene”中的因子变量较少且与“group”中的因子变量不匹配,因此不起作用(引入了NA)

最佳答案

ggplot(test, aes(factor(group, 
                        levels = unique(test[order(test$gene, test$group), "group", drop = TRUE])), 
                 Substance, fill = gene))+
  geom_point(pch = 21, size = 5)+
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))+
  scale_fill_manual(values = gene_palette)+
  theme_classic()

resulting plot

关于r - 在具有较少级别的因子变量之后对 x 轴进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49900585/

相关文章:

r - 如何在ggplot2中绘制参数曲线

r - 使用 "old"ggplot2 代码

r - R 中非数值数据的条形图

r - 使用 Agricolae 包的 R 中没有给出 LSD 的值

R ggplot : Weighted CDF

r - R中的现金流量图?

r - 如何在 ggplot2 中设置 y 轴标签的宽度

r - 如何使用ggplot2修改multiple-ggproto中标签的背景颜色

R geom_tile ggplot2 应用了什么样的统计数据?

r - geom_bar的宽度和间隙(ggplot2)