I'm using ggplot
in R in order to plot some data. What I am trying to do is have a scatter plot where the background is different in different regions of the chart. There is a very helpful answer here that is getting me most of the way there but not all the way.
Here is a sample of the data
row.names selectionDirector country Totals director.rank
1 268 Alfred Hitchcock Argentina 14 1
2 269 Alfred Hitchcock Australia 7 3
3 274 Alfred Hitchcock Canada 10 1
4 286 Alfred Hitchcock France 18 1
5 288 Alfred Hitchcock Germany 9 6
6 296 Alfred Hitchcock Italy 5 3
7 319 Alfred Hitchcock Spain 21 4
8 320 Alfred Hitchcock Sweden 4 8
9 325 Alfred Hitchcock UK 87 1
10 330 Alfred Hitchcock US 87 1
11 346 Andrei Tarkovsky Argentina 4 20
12 347 Andrei Tarkovsky Australia 2 34
13 355 Andrei Tarkovsky Canada 2 32
14 365 Andrei Tarkovsky France 2 37
My code is:
rects <- data.frame(xstart = seq(-0.5,8.5,1), xend = seq(0.5,9.5,1), col = letters[1:10])
ggplot() +
geom_rect(data=rects,aes(ymin=0,ymax=80,xmin=xstart,xmax=xend,fill=col)) +
geom_point(data=top.votes.by.director.country, aes(x=country, y=director.rank)) +
coord_flip() +
facet_wrap(~selectionDirector)
country is a factor with 10 values. director.rank
is numeric. They both come from the data frame top.votes.by.director.country
. The idea is to have a background that is different for the horizontal area for each country to make it easier to read when I facet.
Imagine the picture above except that instead of colored points, there would be a colored band behind a black point for each country. The closest approximation I can find online is the chart below taken from the answer from the link above:
So there would be a colored background for each country in the faceted graph just as the chart above has a colored background for each region.
The problem is that when I run the code above, I get the following error.
Error: Discrete value supplied to continuous scale
When I remove the geom_rect
portion, it works fine. If I move the geom_rect
above the facet_wrap
, I get a chart, although it's messed up. If I do just the geom_rect
part, I get the background I want approximately.
I've been messing around with this for a couple of hours now and can't get it to work.