Search code examples
rplotkernel-density

Show only a certain part of the x-axis when using plot(density(mydf))


There's an extreme value in my data. How can I only show the density plot for the "important" part of my data. I'd like to show the x-axis only from let's say -5 to +5 percent.

COMP <- c("A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B")
RET <- c(-80,1.1,3,1.4,-0.2, 0.6, 0.1, -0.21, -1.2, 0.9, 0.3, -0.1,0.3,-0.12)

mydf <- data.frame(COMP, RET, stringsAsFactors=F)

plot(density(mydf$RET))

and the same with boxplot on the y-axis

boxplot(mydf$RET)

I know

boxplot(mydf$RET, outline=FALSE)

but here I want the range of the y-axis even smaller. How is that possible?

Thank you!


Solution

  • Use the arguments xlim and ylim to adjust the axis' scales in R basic graphics.

    COMP <- c("A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B")
    RET <- c(-80,1.1,3,1.4,-0.2, 0.6, 0.1, -0.21, -1.2, 0.9, 0.3, -0.1,0.3,-0.12)
    mydf <- data.frame(COMP, RET, stringsAsFactors=F)
    
    par(mfrow = c(1,2)) #stack plots in 1 row and 2 columns
    
    plot(density(mydf$RET),xlim=c(-5,5), main="")
    boxplot(mydf$RET, ylim = c(-2,2), ylab="RET")
    

    enter image description here