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

Ale*_*ore 6 r data-visualization ggplot2

ggplot在 R 中使用来绘制一些数据。我想做的是绘制一个散点图,其中图表的不同区域的背景不同。这里有一个非常有用的答案,它让我得到了大部分的帮助,但不是全部。

这是数据示例

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
Run Code Online (Sandbox Code Playgroud)

我的代码是:

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)
Run Code Online (Sandbox Code Playgroud)

国家是一个有 10 个值的因子。director.rank是数字。它们都来自数据框top.votes.by.director.country。这个想法是为每个国家/地区的水平区域提供不同的背景,以便在我刻面时更容易阅读。 在此输入图像描述

想象一下上面的图片,除了每个国家/地区的黑点后面都有一条彩色带,而不是彩色点。我可以在网上找到的最接近的近似值是下面的图表,取自上面链接的答案:

在此输入图像描述

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

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

错误:提供给连续刻度的离散值

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

我已经搞砸了几个小时了,但无法让它发挥作用。

pet*_*932 6

您尝试将离散值绘制为连续刻度时发生错误。在你的例子中,你在 x 中将“国家/地区”绘制为“-0.5~9.5”。您可以更改绘图顺序。

我使用“阿尔弗雷德希区柯克”选择导演通过以下代码进行绘图

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()
Run Code Online (Sandbox Code Playgroud)

结果如下图。

在此输入图像描述

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