R語言柱狀圖排序和x軸上的標簽傾斜操作
R語言做柱狀圖大致有兩種方法, 一種是基礎庫里面的 barplot函數(shù), 另一個就是ggplot2包里面的geom_bar
此處用的是字符變量 統(tǒng)計其各頻數(shù),然后做出其柱狀圖。(橫軸上的標簽顯示不全)
t <- sort(table(dat1$L), decreasing = TRUE) #將頻數(shù)表進行排序
r <- barplot(t, col = "blue",
main = "柱狀圖", ylim = c(0,12), names.arg = dimnames(t) #畫字符變量的柱狀圖
tmp <- as.vector(t) #將頻數(shù)變成一個向量
text(r, tmp, label = tmp, pos = 3) #加柱子上面的標簽
或用ggplot2包 (目前仍沒有給柱子上加數(shù)字標簽)
library(ggplot2) #加載ggplot2包
reorder_size <- function(x) {
factor(x, levels = names(sort(table(x))))
} #自定義函數(shù),獲取因子型變量的因子類型
p <- ggplot(dat3, aes(reorder_size(LAI))) + #用因子變量做基礎底圖,也可直接用reorder排序
geom_bar(fill = "blue") + #畫柱狀圖
theme(axis.text.x = element_text(angle = 45, hjust = 0.5, vjust = 0.5)) + #讓橫軸上的標簽傾斜45度
xlab("柱狀圖") #給x軸加標簽
補充:R 語言條形圖,解決x軸文字排序問題
數(shù)據(jù)結果的圖形展示,R代碼,《R數(shù)據(jù)科學》是個好東西
數(shù)據(jù)格式如下:
| term | category | pval |
| neutrophil chemotaxis | biological_process | 1.68E-09 |
| innate immune response | biological_process | 3.35E-09 |
| complement activation, classical pathway | biological_process | 1.14E-08 |
| negative regulation of endopeptidase activity | biological_process | 4.43E-08 |
| collagen fibril organization | biological_process | 4.43E-08 |
| blood coagulation | biological_process | 1.29E-07 |
| proteolysis involved in cellular protein catabolic process | biological_process | 1.56E-07 |
| proteolysis | biological_process | 1.13E-06 |
| leukocyte migration involved in inflammatory response | biological_process | 1.47E-06 |
| peptide cross-linking | biological_process | 1.47E-06 |
| extracellular space | cellular_component | 8.75E-40 |
| collagen-containing extracellular matrix | cellular_component | 2.08E-26 |
| extracellular matrix | cellular_component | 5.72E-11 |
| lysosome | cellular_component | 6.09E-10 |
| extracellular region | cellular_component | 6.58E-10 |
| collagen trimer | cellular_component | 1.68E-09 |
| cell surface | cellular_component | 2.80E-08 |
| extracellular exosome | cellular_component | 2.34E-07 |
| extrinsic component of external side of plasma membrane | cellular_component | 1.47E-06 |
| sarcolemma | cellular_component | 3.16E-06 |
作圖要求:x軸為term,顏色按categroy分類、并且pval由小到大排序
代碼:
#openxlsx讀入為data.frame class(data) #轉(zhuǎn)換 library(tidyverse) godata<-as_tibble(godata) class(godata) #原始數(shù)據(jù)篩選(category,term,pval)散列,按照category,-log10(pval)排序 data<-godata%>%select(category,term,pval)%>%arrange(category,desc(-log10(pval))) #畫圖時改變geom_bar的自動排序 data$term<-factor(data$term,levels = unique(data$term),ordered = T) #作圖 ggplot(data)+ geom_bar(aes(x=term,y=-log10(pval),fill=category),stat = 'identity')+ coord_flip()
結果:

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
R語言 實現(xiàn)將數(shù)據(jù)框中的字符類型數(shù)字轉(zhuǎn)換為數(shù)值
這篇文章主要介紹了R語言 實現(xiàn)將數(shù)據(jù)框中的字符類型數(shù)字轉(zhuǎn)換為數(shù)值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
R語言數(shù)據(jù)類型與相應運算的實現(xiàn)
本文主要介紹了R語言數(shù)據(jù)類型與相應運算的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03

