I have two data frames, which I want to visualize with lattice's panel dot plot (not ggplot2) using the make.groups()
function to group both data frames. Both data frames contain a variable which should be used conditionally to highlight data by different color fill. So in this case the groups
argument handles the distinction between both data frames by the variable which
generated by make.groups()
.
require(lattice)
# Make reproducable data frame
df= mtcars
df= cbind(car = rownames(df), df)
rownames(df)= NULL
df= df[1:5, c("car", "mpg", "cyl", "carb")]
# Split into 2 dataframes
df.1= df
df.2= df
# Generate slightly different values in 2nd data frame
df.2$mpg= df.2$mpg + rnorm(1,2)
# I am interested to highlight those data which have carb=1
df.1[df.1$carb==1,]
df.2[df.2$carb==1,]
# car mpg cyl carb
#3 Datsun 710 22.8 4 1
#4 Hornet 4 Drive 21.4 6 1
#
# car mpg cyl carb
#3 Datsun 710 25.53714 4 1
#4 Hornet 4 Drive 24.13714 6 1
myTheme= standard.theme(col = FALSE)
myTheme$superpose.symbol$pch= 1:7
par.settings = myTheme
dotplot(car ~ mpg | as.factor(cyl),
data=make.groups(df.1, df.2),
layout=c(3,1),
par.settings = myTheme,
groups = which,
auto.key=TRUE)
This creates a plot:
I'd like to achieve following plot:
How can I refactor the code to achieve this?
Note: This is not a duplicate of Lattice dotplot conditional fill color as the question here is close but different and more complicated. The same answer may not be applied.
After some further research I found the as.layer()
function in the latticeExtra package as a solution.
I am not sure whether this is the most elegant way, but selective highlighting (in this case only colored symbol instead of requested fill) works:
require(latticeExtra)
dotplot(car ~ mpg | as.factor(cyl),
data=make.groups(df.1, df.2),
layout=c(3,1),
par.settings = myTheme,
cex=1,
groups = which,
auto.key=TRUE) +
as.layer(dotplot(car ~ mpg | as.factor(cyl),
data=make.groups(df.1, df.2),
groups=carb<2,
cex=0.5,
pch=19,
col= c("white", "red"))
)
Output: