如何将ggplot2条形图转换为小提琴情节

时间:2016-11-20 15:26:31

标签: r ggplot2 violin-plot

我在some topics进行了搜索,我找到了绘制小提琴情节的主要想法,但是当我将这些剧本组合在一起时(我将在下面展示),结果是不可接受的。似乎从头开始绘制小提琴情节比将条形图转换为小提琴情节更简单。

问:我有一个条形图剧本,我正在尝试转换为小提琴情节(same as this),

在这方面,你能帮我吗? (提前感谢

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)
ggplot(data=dat, aes(x=FunctionClass, y=Frequency, fill=legend)) +
  geom_bar(stat="identity", position=position_dodge(), colour="black")
  scale_colour_gradientn(colours=rainbow(36))

1 个答案:

答案 0 :(得分:0)

我同意@KonradRudolph的观点,即在情节中翻转情节并在标题上显示标签,而不是传说,这是一个更好的方式。请参阅下面的示例。我不认为你需要为条纹着色,但我在下面的例子中留下了颜色。如果各种x值分为几个自然类别,那么根据这些类别进行着色可能更有意义。您还可以使用计数和百分比标记条形图,我也列出了一个示例。

library(ggplot2)

# Create a new label column for the x axis
dat$x = gsub(".: ", "", dat$legend)
dat$x = factor(dat$x, levels=dat$x)

ggplot(data=dat, aes(x=x, y=Frequency, fill=x)) +
  geom_bar(stat="identity", colour="black", show.legend=FALSE) +
  geom_text(aes(
    label=ifelse(Frequency>700, paste0(Frequency, " (",sprintf("%1.1f", Frequency/sum(Frequency)*100),"%)"),
                 ifelse(Frequency>300, Frequency, "")), y=0.5*Frequency), 
    colour="white", size=2.5) +
  scale_colour_gradientn(colours=rainbow(36)) +
  coord_flip() + theme_bw() + labs(x="") 

enter image description here