Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x axis not displaying correctly

Tags:

plot

r

I have the next function that I want to plot:

eq = function(x)
{ a=(sin(5*x)+cos(7*x))^2 
  b= 5 * (1/sqrt(2*pi*0.05)) * exp(-x^2/(2*0.05))
  1-a-b
}

At first I used:

plot(eq(-10:10), type='l')

but then I changed it to:

plot(eq(-10:10), type='l')
axis (1,at=1:21,labels=(-10:10))

Because the x axis wasn't really showing what I needed.

Problem now is that I see some overlaping numbers (a '10' on top of the '-1', etc) not sure why. enter image description here

My ultimate goal would be to display it like this (with a thick line for both x and y axis): enter image description here

like image 566
Chicago1988 Avatar asked Oct 27 '25 10:10

Chicago1988


2 Answers

If you want axes that are at x=0 and y=0, you can add them manually in the base graphics. Here is some example code. The location of text and tick marks might have to be modified.

enter image description here

eq = function(x)
{ a=(sin(5*x)+cos(7*x))^2 
b= 5 * (1/sqrt(2*pi*0.05)) * exp(-x^2/(2*0.05))
1-a-b
}


# basic plot without axes
plot(y=eq(-10:10)
     ,x=c(-10:10)
     ,xaxt='n'
     ,yaxt='n'
     ,type='l'
     ,col='red'
     ,xlab=''
     ,ylab=''
    )
# grid
grid()

# adding thicker horizontal and vertical lines at axis y=0, x=0
abline(h=0,lwd=2,col='black')
abline(v=0,lwd=2,col='black')

# adding text and ticks for x axis, must be modified based on plot
text(x=-0.7,y=seq(1,-8,-1)[-2],seq(1,-8,-1)[-2])
points(x=seq(-10,10,1)[-11],y=rep(0,20),pch='|')

# adding text and ticks for y axis, must be modified based on plot
text(x=c(seq(-10,10,1))[-11],y=-0.4,c(-10:10)[-11])
points(x=rep(0,9),y=seq(-8,1,1)[-9],pch='―')

# adding text for 0-0 point
text(x=-0.3,-0.2,0)
like image 200
Calvin Avatar answered Oct 28 '25 22:10

Calvin


You need to evaluate the function at a finer grid. It might be easier to use curve.

eq <- function(x) {
  a <- (sin(5 * x) + cos(7 * x))^2
  b <- 5 * (1 / sqrt(2 * pi * 0.05)) * exp(-x^2 / (2 * 0.05))
  1 - a - b
}

curve(eq, from = -10, to = 10, n = 10001)
axis(1, at = -10:10)

Created on 2019-03-07 by the reprex package (v0.2.1)

like image 31
dipetkov Avatar answered Oct 29 '25 00:10

dipetkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!