在R语言中用不同标度在同一坐标系内绘制曲线 y1=3xsin(x^3) 在区间 [-2,2] 及 y2=3(x+1)cos(x^3)-|在区间[0,4]的效果图R代码实现
时间: 2024-10-08 10:27:25 浏览: 39
在R语言中,你可以使用`ggplot2`包来在同一坐标系内绘制不同函数的曲线,并通过`scale_y_continuous()`函数调整y轴的范围以适应不同的标度。以下是绘制两个函数`y1 = 3x*sin(x^3)`在区间`[-2, 2]`以及`y2 = 3(x+1)*cos(x^3) - abs(x)`在区间`[0, 4]`的示例代码:
```r
# 首先安装并加载必要的库
if (!require("ggplot2")) install.packages("ggplot2")
library(ggplot2)
# 定义数据框,包含x值
df <- data.frame(
x = seq(-2, 2, by = 0.01), # 对于y1的x范围
y1 = 3 * x * sin(x^3),
x2 = seq(0, 4, by = 0.01), # 对于y2的x范围
y2 = 3 * (x + 1) * cos(x^3) - abs(x)
)
# 绘制第一个函数
p1 <- ggplot(df, aes(x = x, y = y1)) +
geom_line() +
labs(title = "y1 = 3x*sin(x^3)", x = "x", y = expression(3*x*sin(x^3)))
# 绘制第二个函数,需要分开处理因为y2在两个区间有变化
p2_left <- ggplot(df[df$x <= 0, ], aes(x = x2, y = y2)) +
geom_line() +
scale_y_continuous(limits = c(-5, 5), breaks = seq(-5, 5, by = 1)) +
labs(title = "y2 = 3(x+1)cos(x^3) - |x|")
p2_right <- ggplot(df[df$x > 0, ], aes(x = x2, y = y2)) +
geom_line() +
scale_y_continuous(limits = c(-5, 8), breaks = seq(-5, 8, by = 1)) +
labs(title = "y2 = 3(x+1)cos(x^3) - |x| for x in [0, 4]", x = "x", y = "3(x+1)cos(x^3) - |x|")
# 合并两个图形
final_plot <- cowplot::plot_grid(p1, p2_left / p2_right, ncol = 2)
# 显示最终图像
print(final_plot)
```
阅读全文