user149054
user149054

Reputation: 245

Improving Plot in R

Suppose I have the following data:

set.seed(1)

x <- rep(1:54, times=2)
y <- rnorm(108)
indx <- rbinom(54,1, 0.5)
indx.final <- rep(indx,times=2)
sub <- c(rep("(a)", times=54), rep("(b)", times=54))

dat <- data.frame(x, y, indx.final, sub)

I produced the following plot: enter image description here

The necessary R codes are:

par(mfrow=c(2,1))

plot(dat$x[dat$indx.final==1 & dat$sub=="(a)"],dat$y[dat$indx.final==1 & dat$sub=="(a)"],
    ylim=c(-2,2.5), xlab="x-variable",
    ylab="y-variable", pch=19, col="blue", sub="(a)")
points(dat$x[dat$indx.final==0 & dat$sub=="(a)"],dat$y[dat$indx.final==0 & dat$sub=="(a)"],
      pch=19, col="red")
legend("topright",  c("City", "Rural"), pch=19, col=c("blue", "red"))


plot(dat$x[dat$indx.final==1 & dat$sub=="(b)"],dat$y[dat$indx.final==1 & dat$sub=="(b)"],
    ylim=c(-2,2.5), xlab="x-variable",
    ylab="y-variable", pch=19, col="blue", sub="(b)")
points(dat$x[dat$indx.final==0 & dat$sub=="(b)"],dat$y[dat$indx.final==0 & dat$sub=="(b)"],
      pch=19, col="red")
legend("topright", c("City", "Rural"), pch=19, col=c("blue", "red"))

But, the figure is not very appealing. I want to improve few things of the plot: (1)Since x- and y-axis of the both plots are same, I want to reduce the space loss by mentioning x- and y-axis only once rather than twice as it is now, (2)I want the legend only once in the outer margin.

Hence, I was trying xyplot function of lattice library:

##2nd Method:

library(lattice)

xyplot(y~x|sub, data =dat, groups=sub,  layout=c(2,1),  pch=19,  xlab="x-variable", ylab="y-variable") 

It produces the following plot:

enter image description here

Still there are problems in the 2nd plot: (1) I couldn't differentiate the points according to indx.final variable and couldn't add legend. How can I solve both problems?

Upvotes: 0

Views: 37

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You could recreate this plot with a lot less effort and much more scope for customization using ggplot:

library(ggplot2)

ggplot(dat, aes(x, y, color = factor(indx.final))) +
  geom_point() +
  facet_grid(sub~.) +
  scale_color_manual(values = c("blue", "red"),
                     labels = c("City", "Rural"), name = "") +
  theme_bw()

enter image description here

Upvotes: 2

Related Questions