如何在R中使用x轴和y轴绘制图形?

时间:2019-08-10 00:39:44

标签: r

我有一个功能

x= (z-z^2.5)/(1+2*z-z^2) 
y = z-z^2.5

其中z是唯一变量。如何绘制图形,其中x-axis的范围为xy-axis显示函数y的值,而z显示函数0 to 5的值?

2 个答案:

答案 0 :(得分:2)

只需遵循您自己的说明,您就能获得非常基本的情节。

## z ranges from 0 to 5
z = seq(0,5,0.01)

## x and y are functions of z
x = (z-z^2.5)/(1+2*z-z^2)
y = z-z^2.5

##plot
plot(x,y, pch=20, cex=0.5)

plot of x and y

如果您想要平滑的曲线,会有些棘手。的曲线不连续
z = 1 + sqrt(2) ~ 2.414。如果仅将曲线绘制为一条,则会在不连续处连接一条多余的线。因此,分为两部分,

plot(x[1:242],y[1:242], type='l', xlab='x', ylab='y',
    xlim=range(x), ylim=range(y))
lines(x[243:501],y[243:501])

Smooth curve

但是在解释这一点时要小心。从z = 0到z = 1有一些棘手的事情。

答案 1 :(得分:1)

使用ggplot2

# z ranges from -1000 to 1000 (The range can be arbitrary)
z = seq(-1000,1000,.25)

# x as a function of z
x = (z-z^2.5) / ((1+2*z)-z^2)

# y as a function of z
y = z-z^2.5

# make a dataframe of x,y and z
df <- data.frame(x=x, y=y, z=z)

# subset the df where z is between 0 and 5
df_5 <- subset(df, (df$z>=0 & df$z<=5))

# plot the graph
library(ggplot2)
ggplot(df_5, aes(x,y))+ geom_point(color="red")

xy as a function of Z

@ G5W答案的唯一补充是从数据集中绘制subset()0的{​​{1}}和5之间的值。