R语言做柱状图大致有两种方法, 一种是基础库里面的 barplot函数, 另一个就是ggplot2包里面的geom_bar
此处用的是字符变量 统计其各频数,然后做出其柱状图。(横轴上的标签显示不全)
1
2
3
4
5
|
t <- sort (table(dat1$L), decreasing = TRUE) #将频数表进行排序
r <- barplot(t, col = "blue" ,
main = "柱状图" , ylim = c(0,12), names.arg = dimnames(t) #画字符变量的柱状图
tmp <- as.vector(t) #将频数变成一个向量
text(r, tmp, label = tmp, pos = 3) #加柱子上面的标签
|
或用ggplot2包 (目前仍没有给柱子上加数字标签)
1
2
3
4
5
6
7
8
|
library(ggplot2) #加载ggplot2包
reorder_size <- function (x) {
factor(x, levels = names( sort (table(x))))
} #自定义函数,获取因子型变量的因子类型
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轴文字排序问题
数据结果的图形展示,R代码,《R数据科学》是个好东西
数据格式如下:
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由小到大排序
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#openxlsx读入为data.frame
class(data)
#转换
library(tidyverse)
godata<-as_tibble(godata)
class(godata)
#原始数据筛选(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()
|
结果:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/qq_35242986/article/details/69503875