1 默认plot(来自参考)
创建函数
# Create own functions
my_fun1 <- function(x) { x^3 - x * 300 }
my_fun2 <- function(x) { x^3 * 2 + x^2 + x * 10 + 5 * 10^10 }
my_fun3 <- function(x) { - x^3 + x^2 - 2 * 10^10 }
plot 保存
pdf("test_plot.pdf")
curve(my_fun1, from = -5000, to = 5000, col = 2) # Draw Base R plot
curve(my_fun2, from = -5000, to = 5000, col = 3, add = TRUE)
curve(my_fun3, from = -5000, to = 5000, col = 4, add = TRUE)
dev.off()
2 ggplot(来自参考)
统合公式,ggplot准备
library("ggplot2")
# Create data for ggplot2
data_fun <- data.frame(x = -5000:5000,
values = c(my_fun1(-5000:5000),
my_fun2(-5000:5000),
my_fun3(-5000:5000)),
fun = rep(c("fun1", "fun2", "fun3"),
each = 10001))
head(data_fun)
ggplot
# Draw ggplot2 plot
ggplot(data_fun, aes(x, values, col = fun)) +
geom_line()
3 一个ggplot绘制公式曲线案例
函数参数
a1 = 4319.64; b1 = 0.229837
a2 = 2486.19; b2 = 0.157168
a3 = 2015.95; b3 = 0.185205
写好函数
my_fun1 <- function(x) {a1 * x^b1}
my_fun2 <- function(x) {a2 * x^b2}
my_fun3 <- function(x) {a3 * x^b3}
普通曲线
curve(my_fun1, from = 0, to = 16, col = 2)
curve(my_fun2, from = 0, to = 22, col = 3, add = TRUE)
curve(my_fun3, from = 0, to = 16, col = 4, add = TRUE)
准备ggplot数据框
准备x,用函数计算y,ggplot line即可出结果
library("ggplot2")
data <- data.frame(x = c(1:16,
1:22,
1:16),
values = c(my_fun1(1:16),
my_fun2(1:22),
my_fun3(1:16)),
fun = c(rep("Escherichia flexneri", 16),
rep("Enterococcus faecalis", 22),
rep("Lactobacillus amylovorus", 16)))
准备标签和颜色
genomes = c("Escherichia flexneri",
"Limosilactobacillus reuteri",
"Enterococcus faecalis")
genomes = factor(genomes, levels = genomes)
col_list = read.table("C:/Users/hutongyuan/Desktop/group_color.list",sep="\t", check.names=F, na.string="", stringsAsFactors=F, quote="", comment.char="")
colors = col_list$V1[1:3]
names(colors) <- genomes
ggplot
技巧
1 scale_x_continous 设置x轴标签
2 scale_color_manual 使用配置颜色
3 theme(legend.posiotn = c()) 任意设置legend位置
pic =
ggplot(data, aes(x, values, col = fun)) +
geom_line(size = 1) +
theme_classic() +
labs(x = "Number of Genomes",
y = "Number of Pangenome Families",
color = "") +
theme(legend.text = element_text(size=15),
legend.title = element_text(face='bold', size=20),
legend.position = c(0.75, 0.7),
legend.background = element_rect(color = "black",
linetype = "solid",
size = 1)) +
theme(axis.text.x = element_text(size = 15),
axis.text.y = element_text(size = 18),
axis.title = element_text(size = 22),
axis.line = element_line(size = 1),
axis.ticks = element_line(size = 1)) +
scale_color_manual(values = colors) +
scale_x_continuous(limits = c(1, 50),
breaks = c(1, 10, 20, 30, 40, 50))
ggsave(pic, filename = "all_pan_curve_test.pdf", width = 8)
参考:
Draw Multiple Function Curves to Same Plot in R (2 Examples)
R语言作图:数学公式 【公式书写】
网友评论