R语言ggplot2绘制折线图并添加下降指数拟合曲线

本文介绍使用R语言ggplot2包绘制折线图并添加下降指数拟合曲线。

绘制基础折线图

首先,我们使用ggplot()函数创建基础折线图:

ggplot(data_zhexian2, aes(Peptides, LncRNAs)) + 
  geom_line(color = '#fc8080') + 
  geom_point(color = '#7e80ff', size = 3) + 
  labs(y = 'Log(LncRNAs)') + 
  theme_bw() + 
  theme(axis.ticks.length = unit(2, 'pt'),
        legend.key.width = unit(10, 'pt'),
        panel.grid = element_line(size = 0.1),
        axis.text = element_text(color = 'black', family = 'serif', size = 10),
        axis.title = element_text(color = 'black', family = 'serif', size = 12),
        axis.ticks = element_line(size = 0.3, color = 'black'),
        axis.line = element_line(size = 0.3, color = 'black'))

添加下降指数拟合曲线

可以使用geom_smooth函数添加一个下降指数拟合曲线,如下所示:

ggplot(data_zhexian2, aes(Peptides, LncRNAs)) + 
  geom_line(color = '#fc8080') + 
  geom_point(color = '#7e80ff', size = 3) + 
  geom_smooth(method = 'nls', formula = y ~ a * exp(-b * x), se = FALSE, color = '#4e4e4e') + 
  labs(y = 'Log(LncRNAs)') + 
  theme_bw() + 
  theme(axis.ticks.length = unit(2, 'pt'),
        legend.key.width = unit(10, 'pt'),
        panel.grid = element_line(size = 0.1),
        axis.text = element_text(color = 'black', family = 'serif', size = 10),
        axis.title = element_text(color = 'black', family = 'serif', size = 12),
        axis.ticks = element_line(size = 0.3, color = 'black'),
        axis.line = element_line(size = 0.3, color = 'black'))

其中,method = 'nls'表示使用非线性最小二乘法拟合曲线,formula = y ~ a * exp(-b * x)表示使用下降指数函数进行拟合,se = FALSE表示不显示拟合曲线的置信区间,color = '#4e4e4e'表示设置拟合曲线的颜色。

代码解释

  • ggplot(data_zhexian2, aes(Peptides, LncRNAs)):使用ggplot()函数创建基础图形,将数据 data_zhexian2 中的 Peptides 列作为 x 轴,LncRNAs 列作为 y 轴。
  • geom_line(color = '#fc8080'):添加折线,并设置颜色为 #fc8080(浅红色)。
  • geom_point(color = '#7e80ff', size = 3):添加数据点,并设置颜色为 #7e80ff(浅蓝色),大小为 3。
  • geom_smooth(method = 'nls', formula = y ~ a * exp(-b * x), se = FALSE, color = '#4e4e4e'):添加下降指数拟合曲线,设置参数如下:
    • method = 'nls':使用非线性最小二乘法拟合曲线。
    • formula = y ~ a * exp(-b * x):使用下降指数函数进行拟合。
    • se = FALSE:不显示拟合曲线的置信区间。
    • color = '#4e4e4e':设置拟合曲线的颜色。
  • labs(y = 'Log(LncRNAs)'):设置 y 轴标签。
  • theme_bw():使用白色背景主题。
  • theme():自定义图表样式,包括:
    • axis.ticks.length = unit(2, 'pt'):设置刻度线长度。
    • legend.key.width = unit(10, 'pt'):设置图例宽度。
    • panel.grid = element_line(size = 0.1):设置网格线大小。
    • axis.text = element_text(color = 'black', family = 'serif', size = 10):设置坐标轴文本样式。
    • axis.title = element_text(color = 'black', family = 'serif', size = 12):设置坐标轴标题样式。
    • axis.ticks = element_line(size = 0.3, color = 'black'):设置刻度线大小。
    • axis.line = element_line(size = 0.3, color = 'black'):设置坐标轴线大小。

总结

通过以上代码,我们就可以在R语言中使用ggplot2包绘制折线图并添加下降指数拟合曲线,并通过自定义主题样式来美化图表。

R语言ggplot2绘制折线图并添加下降指数拟合曲线

原文地址: https://www.cveoy.top/t/topic/mGHg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录