Удвоение столбцов на оси x, сохраняя при этом одну общую легенду в ggplot - PullRequest
0 голосов
/ 28 января 2020

У меня есть следующий график в R:

dat <- data.frame(
  FunctionClass = factor(c("A", "B", "C", "D", "E", "F", "G", "H", "I",     "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "Z"), levels=c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "Z")),
  legend = c("A: RNA processing and modification", "B: Chromatin structure and dynamics", "C: Energy production and conversion", "D: Cell cycle control, cell division, chromosome partitioning", "E: Amino acid transport and metabolism", "F: Nucleotide transport and metabolism", "G: Carbohydrate transport and metabolism", "H: Coenzyme transport and metabolism", "I: Lipid transport and metabolism", "J: Translation, ribosomal structure and biogenesis", "K: Transcription", "L: Replication, recombination and repair", "M: Cell wall/membrane/envelope biogenesis", "N: Cell motility", "O: Posttranslational modification, protein turnover, chaperones", "P: Inorganic ion transport and metabolism", "Q: Secondary metabolites biosynthesis, transport and catabolism", "R: General function prediction only", "S: Function unknown", "T: Signal transduction mechanisms", "U: Intracellular trafficking, secretion, and vesicular transport", "V: Defense mechanisms", "W: Extracellular structures", "Y: Nuclear structure", "Z: Cytoskeleton"),
  Frequency=c(360,391,897,1558,1168,448,1030,536,732,1292,2221,2098,789,117,1744,732,437,5162,1251,2191,603,216,2,14,739)
)

library(ggplot2)

p <- ggplot(data=dat, aes(x=FunctionClass, y=Frequency, fill=legend))+
  geom_bar(stat="identity", position=position_dodge(), colour="seashell")
p + guides (fill = guide_legend(ncol = 1))+
  xlab("COG Class")+
  ggtitle("COG distribution")


Моя цель - иметь два бара для "A", два бара для "B" и c вместо одного. Мне, конечно, придется кормить R данными, содержащими другие частоты. Они выглядят так:

Frequency2=c(523,900,400,155,168,428,1050,516,742,129,221,2698,7829,1147,144,7132,4437,562,1551,2691,103,516,22,12,939)

Однако я не могу понять, как их включить. Кроме того, я хотел бы просто оставить одну общую легенду (описание того, что обозначают различные буквы).

Может кто-нибудь подтолкнуть меня в правильном направлении? Я не могу найти информацию об этом на сайте ggplots.

1 Ответ

0 голосов
/ 28 января 2020

Помогает ли это?

library(tidyverse)

dat <- data.frame(
    FunctionClass = factor(c("A", "B", "C", "D", "E", "F", "G", "H", "I",     "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "Z"), levels=c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y", "Z")),
    legend = c("A: RNA processing and modification", "B: Chromatin structure and dynamics", "C: Energy production and conversion", "D: Cell cycle control, cell division, chromosome partitioning", "E: Amino acid transport and metabolism", "F: Nucleotide transport and metabolism", "G: Carbohydrate transport and metabolism", "H: Coenzyme transport and metabolism", "I: Lipid transport and metabolism", "J: Translation, ribosomal structure and biogenesis", "K: Transcription", "L: Replication, recombination and repair", "M: Cell wall/membrane/envelope biogenesis", "N: Cell motility", "O: Posttranslational modification, protein turnover, chaperones", "P: Inorganic ion transport and metabolism", "Q: Secondary metabolites biosynthesis, transport and catabolism", "R: General function prediction only", "S: Function unknown", "T: Signal transduction mechanisms", "U: Intracellular trafficking, secretion, and vesicular transport", "V: Defense mechanisms", "W: Extracellular structures", "Y: Nuclear structure", "Z: Cytoskeleton"),
    Frequency=c(360,391,897,1558,1168,448,1030,536,732,1292,2221,2098,789,117,1744,732,437,5162,1251,2191,603,216,2,14,739)
)

dat <- cbind(
    dat
    , Frequency2=c(523,900,400,155,168,428,1050,516,742,129,221,2698,7829,1147,144,7132,4437,562,1551,2691,103,516,22,12,939))

dat %>%
    gather("variable", "value", -FunctionClass, -legend) %>%
    ggplot(aes(FunctionClass, value, fill = legend, group = variable)) +
    geom_bar(stat="identity", position=position_dodge(), colour="seashell") +
    guides (fill = guide_legend(ncol = 1)) +
    xlab("COG Class") +
    ggtitle("COG distribution")

enter image description here

Что здесь происходит, так это то, что я добавляю дополнительный столбец в фрейм данных (cbind()) а затем превратить его из широкого формата в длинный (gather()). Последнее, что нужно сделать, это ввести новый столбец variable как group aestheti c.

...