[英]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. 其中
z
是唯一的变量。 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
? 如何绘制图形,其中
x-axis
显示函数x
值, y-axis
显示函数y
值,因为z
范围从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)
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
. 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.
从z = 0到z = 1有一些棘手的问题。
Using ggplot2
使用
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")
The only addition to @G5W answer is subset()
of values between 0
and 5
from your dataset to plot and the use of ggplot2
. @ G5W答案的唯一补充是从数据集到绘图和使用
ggplot2
0
到5
之间的值subset()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.