Play a chart in R

Asked

Viewed 158 times

4

I made graph 1 below in R, from the code:

library(truncreg)
set.seed(1)
x  <- sort(rnorm(50)+3)
y  <- 3 + 1*x + rnorm(50,0,0.3)

compl <- data.frame(x,y)
y[y>6.5] <- 6.5
sample <- data.frame(x,y)

pred.OLS   <- predict(       lm(y~x, data=sample) )
pred.trunc <- predict( truncreg(y~x, data=compl,point = 12.04,direction = "right"))

plot( compl$x, compl$y,  pch= 1,xlab="x",ylab="y",ylim=NULL,xlim=NULL)
points(sample$x,sample$y,  pch=16)
lines( sample$x,pred.OLS,  lty=2,lwd=2)
lines( compl$x,pred.trunc,lty=1,lwd=2)
abline(h=6.5,lty=3)        # horizontal line at 0
abline(v=3.5,lty=3)

Figura 1

However, my wish is to make this chart:

inserir a descrição da imagem aqui

Does anyone know how I can proceed? I have not found how to remove the numerical values from the axes nor how to add the intercepts $k$ e $x_{0}.$ If you have suggestions on how to do with ggplot, I am even more grateful!

2 answers

4


Using ggplot2:

library(ggplot2)

dados <- data.frame(x=x, y_original=compl$y, y_trunc=sample$y, OLS=pred.OLS, trunc=pred.trunc)

ggplot(dados, aes(x=x)) +
  geom_point(aes(y=y_original), shape = 21, fill="white") +
  geom_point(aes(y=y_trunc), shape = 21, fill="black") +
  geom_line(aes(y=OLS), linetype="dashed") +
  geom_line(aes(y=trunc)) +
  labs(x="x", y="y") +
  scale_x_continuous(breaks=3.5, labels=expression(x[0])) +
  scale_y_continuous(breaks=6.5, labels="k") +
  geom_segment(aes(x=3.5, y=2.47, xend=3.5, yend=6.5), linetype="dotted") +
  geom_segment(aes(x=-0.25, y=6.5, xend=5, yend=6.5), linetype="dotted") +
  theme(legend.position="bottom", legend.title=element_blank(),
        legend.key = element_rect(colour = 'white'), 
        legend.background = element_rect(colour = "black"), 
        panel.border = element_blank(), 
        axis.line = element_line(), 
        panel.background = element_rect(fill = "white", colour = "white"))

inserir a descrição da imagem aqui

3

On a Plot basis:

plot( compl$x, compl$y,  pch= 1,xlab="x",ylab="y",ylim=NULL,xlim=NULL,axes = F)
axis(1, at=c(0, 3.5, max(compl$x)), labels = c("", expression(x[0]), ""), lwd.tick=0)
axis(2, at=c(0, 6.5, max(compl$y)), labels = c("", "k", ""), lwd.tick=0, las = 1)
points(sample$x,sample$y,  pch=16)
lines( sample$x,pred.OLS,  lty=2,lwd=2)
lines( compl$x,pred.trunc,lty=1,lwd=2)
abline(h=6.5,lty=3)        
abline(v=3.5,lty=3)

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.