使用因子变量更改 ggplot 图表的背景颜色

Changing the background color of a ggplot chart with a factor variable

我在 R 中使用 ggplot 来绘制一些数据。我想要做的是绘制一个散点图,其中图表不同区域的背景不同。有一个非常有用的答案 here 让我了解了大部分内容,但并非所有内容。

这是数据样本

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

我的代码是:

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)

国家是一个有 10 个值的因素。 director.rank 是数字。它们都来自数据框top.votes.by.director.country。这个想法是让每个国家/地区的水平区域都有不同的背景,以便在我分面时更容易阅读。

想象一下上面的图片,除了彩色点之外,每个国家/地区的黑点后面都会有一条彩色带。我在网上能找到的最接近的近似值是下面的图表,摘自上面 link 的答案:

所以多面图中的每个国家/地区都会有一个彩色背景,就像上面的图表每个地区都有一个彩色背景一样。

问题是,当我 运行 上面的代码时,出现以下错误。

Error: Discrete value supplied to continuous scale

当我删除 geom_rect 部分时,它工作正常。如果我将 geom_rect 移到 facet_wrap 上方,我会得到一个图表,尽管它很乱。如果我只做 geom_rect 部分,我会得到大约我想要的背景。

我已经弄乱这个几个小时了,但无法让它工作。

错误发生在您尝试将离散值绘制成连续比例时。 在您的情况下,您将 "country" 绘制为 x 中的“-0.5~9.5”。你可以改变你的绘图顺序。

我使用了"Alfred Hitchcock" selectionDirector 通过以下代码绘制

rects <- data.frame(xstart = seq(0.5,9.5,1), xend = seq(1.5,10.5,1), 
         col = letters[1:10])
ggplot() + geom_point(data=top.votes.by.director.country, 
                      aes(x=country, y=director.rank)) +
           geom_rect(data=rects, aes(ymin=0, ymax=80, xmin=xstart,
                      xmax=xend, fill=col), alpha =0.5) + coord_flip()

结果如下图。

注意:我将矩形的 x 移动了“1”(从 0.5 开始,而不是 -0.5),并为矩形添加了 alpha 属性。