简体   繁体   中英

How to draw a graph with both x-axis and y-axis are functions in R?

I have a function,

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

where z is the only variable. How to draw a graph where x-axis shows value of function x , and y-axis shows value of function y as z range from 0 to 5 ?

You can get a very basic plot by simply following your own instructions.

## 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)

x和y的图

If you want a smooth curve it is a little trickier. There is a discontinuity in the curve at
z = 1 + sqrt(2) ~ 2.414 . If you just draw the curve as one piece, you get an unwanted line connecting across the discontinuity. So, in two pieces,

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])

光滑的曲线

But be careful about interpreting this. There is something tricky going on from z=0 to z=1.

Using 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是Z的函数

The only addition to @G5W answer is subset() of values between 0 and 5 from your dataset to plot and the use of ggplot2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM