Reputation: 1041
I have the following data frame:
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"))
And I have this plot:
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()
This produces the following plot:
Is there a way to sort the order of "groups" on the x-axis so that each gene will be next to eachother on the x axis, in the order listed in the legend? This way, the color for each gene type will be next to each other.
I tried the solutions presented here, but since the factor variables in "gene" is fewer and doesn't match the ones in "group", that didn't work (introduced NA's)
Upvotes: 2
Views: 45
Reputation: 132576
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()
Upvotes: 3