ggplot2 scale_brewer的逆序

时间:2012-01-05 22:35:59

标签: r ggplot2

看起来这是一件非常简单的事情,但是我花了> 30分钟没有找到答案。

如何反转颜色顺序?通过查看documentation for scale_brewer,我认为可能formatter=论证是可疑的。我通过'rev'然后rev,但它们没有效果(没有错误消息,只是被忽略)。

6 个答案:

答案 0 :(得分:53)

我想您可能想直接使用brewer.pal选择颜色,然后使用scale_colour_manual

ggplot(mtcars,aes(x = mpg, y = disp)) + 
    geom_point(aes(colour = factor(cyl))) + 
    scale_colour_manual(values = rev(brewer.pal(3,"BuPu")))

然后你可以rev那里的颜色顺序。

从ggplot版本2.0,0开始,现在有更直接的方法,请参阅下面的@pbaylis的答案。

答案 1 :(得分:47)

ggplot2的CRAN版本现在允许用户在scale_brewer中指定direction=-1来反转颜色。以下内容与接受的答案产生相同的图表。

ggplot(mtcars,aes(x = mpg, y = disp)) + 
  geom_point(aes(colour = factor(cyl))) + 
  scale_colour_brewer(palette="BuPu", direction=-1)

答案 2 :(得分:23)

这对OP的问题没有帮助 - 我知道。对于像scale_..._brewer()这样的离散量表,执行scale_..._manual(values = rev(colorsYouHad))是正确答案。

然而,对于连续比例,您只需传递:

scale_..._...(..., trans = "reverse")

例如,对于连续等效的scale_..._brewer()

scale_..._distiller("My Scale", palette = "Spectral", trans = "reverse")

答案 3 :(得分:11)

如果您不想直接使用RColorBrewer(一个可爱的包),您可以反转原始data.frame中的因子级别,然后绘制它:

dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 

# Reverse the levels of the factor associated with color, here 'clarity'
# (Might be safer to assign this to a new column named, e.g., 'clarity2')
levels(dsamp$clarity) <- rev(levels(dsamp$clarity))

d <- qplot(carat, price, data = dsamp, colour = clarity)
d + scale_colour_brewer(breaks = levels(dsamp$clarity))

如果您想以与撤消前相同的顺序打印密钥,请执行以下操作:

d + scale_colour_brewer(breaks = rev(levels(dsamp$clarity)))

答案 4 :(得分:4)

我知道,晚会很晚。但是我前一段时间遇到了这个问题,并使用了上面的解决方案。我目前正在查看Hadley Wickham撰写的r4ds,并且有一个非常简单的解决方案,因此我认为应该发布它。更改此:

ggplot(mtcars,aes(x = mpg, y = disp)) + 
geom_point(aes(colour = factor(cyl)))

对此:

ggplot(mtcars,aes(x = mpg, y = disp)) + 
geom_point(aes(colour = factor(-cyl))) #note the minus symbol

答案 5 :(得分:1)

我收到一个错误,说负号不适用于因子。我正在使用灰度而不是啤酒酿造商,也许这是错误的根源?对于scale_color_grey,我发现将起始点和结束点从默认工作方式反转了。

# lighter shade for first category (default)
+ scale_color_grey(start = 0.2, end = 0.8) 

# darker shade for first category 
+ scale_color_grey(start = 0.8, end = 0.2)