Reputation: 3104
I have a data frame, which I want to visualize with lattice's panel dot plot (not ggplot2). It contains a variable which should be used conditionally to highlight data by different color fill.
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")]
df
# output:
# car mpg cyl carb
# Mazda RX4 21.0 6 4
# Mazda RX4 Wag 21.0 6 4
# Datsun 710 22.8 4 1
# Hornet 4 Drive 21.4 6 1
# Hornet Sportabout 18.7 8 2
# I am interested to highlight those data which have carb=1
df[df$carb==1,]
# car mpg cyl carb
# Datsun 710 22.8 4 1
# Hornet 4 Drive 21.4 6 1
dotplot(car ~ mpg | as.factor(cyl), data=df, layout=c(3,1))
This creates a plot:
I'd like to achieve following plot:
How can I refactor the code to achieve this?
Upvotes: 4
Views: 2085
Reputation: 67778
You may try this:
dotplot(car ~ mpg | as.factor(cyl), data=df, layout=c(3,1),
pch = 19, groups = carb < 2, col = c("blue", "red"))
The groups
argument carb < 2
results in a logical vector. Alphabetically FALSE
comes before TRUE
. Thus, cases where carb < 2
is FALSE get the first colour (blue), and cases where carb < 2 get the second colour, red.
From ?dotplot
about group
argument:
A variable or expression to be evaluated in data, expected to act as a grouping variable within each panel, typically used to distinguish different groups by varying graphical parameters like color and line type.
Upvotes: 6