Plotting Confidence Intervals in XYplot: A Month-Specific Approach Using Custom Subscripts

The issue with your code is that you are trying to plot confidence intervals for each month separately in all panels. However, the subplots in xyplot are created automatically based on the data, so you need to specify which subplots correspond to which months.

To achieve this, you can use the subscripts argument in the panel function to select specific data points that correspond to each month. Here’s an updated code snippet:

xyplot(Mean_cpue~as.factor(Year)|as.factor(Month) ,data=meancpue,xlab="Year", ylab="Index",col="black",
       panel=function(x,y,...){
           panel.xyplot(x, y)
           # Select data points for each month
           subscripts <- ifelse(as.factor(meancpue$Month)==1, 1:6, 
                                ifelse(as.factor(meancpue$Month)==2, 7:12, 
                                       ifelse(as.factor(meancpue$Month)==3, 13:18, 
                                              ifelse(as.factor(meancpue$Month)==4, 19:24, NA))))
           # Plot confidence intervals
           panel.xyplot(as.factor(meancpue$Year)[subscripts], meancpue$lower[subscripts], type="l", col = "red", lty = 3,lwd=1)
           panel.xyplot(as.factor(meancpue$Year)[subscripts], meancpue$upper[subscripts], type="l", col = "blue", lty=3,lwd = 1)
       },
       scales=list(y=list(alternating=1,cex=0.8,relation="free"),x=list(alternating=1,cex=.8,rot=90)),
       strip = strip.custom(bg="white" , strip.levels = T))

In this updated code, we use ifelse statements to select the data points for each month based on their corresponding factor levels. We then plot these selected data points with confidence intervals.

Note that I’ve also removed the subplots argument and replaced it with subscripts=T, which allows us to specify custom subscripts for each panel.


Last modified on 2023-11-08