看似非常简单的事情,但我花了30分钟没有找到答案.
如何反转颜色顺序?通过查看scale_brewer的文档,我认为它可能是formatter=可疑的论点.我通过'rev'然后rev,但它们没有效果(没有错误信息,只是被忽略).
jor*_*ran 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")))
Run Code Online (Sandbox Code Playgroud)
然后你可以rev在那里的颜色的顺序.
从ggplot版本2.0,0开始,现在有更直接的方法,请参阅下面的@pbaylis的答案.
pba*_*lis 50
ggplot2的CRAN版本现在允许用户direction=-1在scale_brewer中指定反转颜色.以下内容与接受的答案生成相同的图.
ggplot(mtcars,aes(x = mpg, y = disp)) +
geom_point(aes(colour = factor(cyl))) +
scale_colour_brewer(palette="BuPu", direction=-1)
Run Code Online (Sandbox Code Playgroud)
Ant*_*zée 25
这对OP的问题没有帮助 - 我知道.对于离散比例scale_..._brewer(),做,scale_..._manual(values = rev(colorsYouHad))是正确的答案.
然而,对于连续比例,您可以简单地通过:
scale_..._...(..., trans = "reverse")
例如,对于连续相当于scale_..._brewer():
scale_..._distiller("My Scale", palette = "Spectral", trans = "reverse")
Jos*_*ien 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))
Run Code Online (Sandbox Code Playgroud)
如果您想以与反转之前相同的顺序打印密钥,只需执行以下操作:
d + scale_colour_brewer(breaks = rev(levels(dsamp$clarity)))
Run Code Online (Sandbox Code Playgroud)