如何用R的ggplot2绘制正弦函数并定位到x轴指定坐标处
实现方法
方法1:无需修改原有数据框,直接调整偏移量
你当前的x_1是取值范围为[-1, 1]的正弦波动值,默认以0为水平中心,要让四条曲线分别以x=1、x=2、x=3、x=4为中心,直接修改geom_path里x轴映射的偏移值即可:
library(ggplot2) library(tibble) df <- data.frame(x = 0:10, y = 0:10) curve <- tibble( z_1 = seq(0, 20, length.out = 1500),x_1 = sin(z_1), z_2 = sin(x_1)+2, z_3 = sin(x_1)+5) base <- ggplot(df, aes(x, y)) + geom_blank() base + geom_path(data = curve, aes(x = x_1 + 1,y = z_1), color ='red')+ geom_path(data = curve, aes(x = x_1 + 2,y = z_1), color ='red')+ geom_path(data = curve, aes(x = x_1 + 3,y = z_1), color ='red')+ geom_path(data = curve, aes(x = x_1 + 4,y = z_1), color ='red')
方法2:重构数据框为长格式,代码更简洁易维护
如果后续要调整曲线数量、样式,推荐把数据重构为长格式,不需要重复写多次geom_path:
library(ggplot2) library(tibble) library(tidyr) library(dplyr) df <- data.frame(x = 0:10, y = 0:10) curve <- tibble( z_1 = seq(0, 20, length.out = 1500),x_1 = sin(z_1)) # 生成四个中心坐标,和原数据交叉连接 curve_long <- curve %>% crossing(center_x = c(1,2,3,4)) %>% mutate(x_final = x_1 + center_x) ggplot(df, aes(x, y)) + geom_blank() + # 按center_x分组,一次性绘制四条曲线 geom_path(data = curve_long, aes(x = x_final, y = z_1, group = center_x), color = 'red')
内容的提问来源于stack exchange,提问作者Laura
相关产品推荐
相关产品推荐

