Search code examples
rpanellattice

superimpose barchart with stripplot


I want to superimpose barchart with stripplot, and use panel paremeter in the xyplot, but it doesn't work. It plots nothing and give out many warnings, such as:

1: In order(as.numeric(x)) : NAs introduced by coercion
2: In diff(as.numeric(x[ord])) : NAs introduced by coercion

The code is here, however it works with the factorial Alternatice and Subject variables, although it plot the bar in a horizontal way:

t2 <- data.frame(Alternative = c("FA", "HF", "NO", "HF", "FA", "NO"), 
  AlloOthe = c(50, 80, 20, 80, 80, 20), 
  Subject = rep(c("2001", "2002"), each = 3)
)
t2$Alternative <- as.character(t2$Alternative)
t2$Subject <- as.character(t2$Subject)
library(lattice)
xyplot(AlloOthe ~ Alternative | Subject, data = t2,
  panel = function(x, y) {
    panel.barchart(x, y)
    panel.stripplot(x, y, type = c("p", "l"))
  },
  ylab = "Allocation to Other"
)

So does anyone could show me the correct code or to make it work on the right data? Thanks a lot!


Solution

  • I am not an expert in lattice package, but I get your plot by following this post: Add stripplot points to bwplot (Lattice graphics in R), so, I add ... to the panel function definition and also I replaced xyplot by barchart.

    SO, basically, it looks like:

    # Assigning Alternative and Subject as factor
    t2$Alternative = as.factor(t2$Alternative)
    t2$Subject = as.factor(t2$Subject)
    
    library(lattice)
    barchart(AlloOthe ~ Alternative | Subject, data = t2,
             panel = function(x,y,...) {
               panel.barchart(x,y,col=adjustcolor("darkorchid",alpha=.6),...)
               panel.stripplot(x,y,col="lightseagreen",pch=16,size=3,...)
             },
             ylab = "Allocation to Other")
    

    And the plot looks like:

    enter image description here

    As an alternative, you can use ggplot by doing the following:

    library(ggplot2)
    ggplot(t2, aes(x = Alternative, y = AlloOthe, group = Alternative)) +
      facet_grid(.~Subject) +
      geom_bar(stat = "identity", fill = adjustcolor("darkorchid", alpha = 0.6)) +
      geom_point(size = 3, color = "lightseagreen") +
      ylab("Allocation to Other")
    
    

    And the plot looks like:

    enter image description here

    Hope it helps you !