使用ggplot2生成带偏移标签的颜色图例 [英] Generating a color legend with shifted labels using ggplot2

查看:134
本文介绍了使用ggplot2生成带偏移标签的颜色图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常使用GrADS绘制地图,通常我会使用图中的颜色图例:

我想在R中使用ggplot2来做同样的事情。如果使用简单的话:

  g < -  g + scale_fill_brewer(palette =Greens,na.value =NA,name = legendtitle)
#g是之前保存的一些图简单的选项,准备cut()

输出当然是这样的:





因此,我希望能够做到两件事:


  1. 移动标签,使其位于颜色之间,注意指示上述间隔(注意:重命名标签并不是问题,将它们转换为)

  2. 最后一个标签应该是箭头状的,以表明最大值(例子中为10)最深的颜色(深绿色) )

编辑:
使用下面答案的帮助,我已经看到:



第1部分:我的问题几乎解决了,即使它看起来不完美。我真的很想摆脱颜色之间的空白,任何想法?第2部分...我不知道什么。

我的代码片段使用:

theme(legend.position = bottom,legend.key.width = unit(1,cm),legend.key.height = unit(0.3,cm))+ guides(fill = guide_legend(label.position =bottom,label .hjust = 1.2))

解决方案



想法是使用 cut()创建分割点,但是按照您的需要指定标签。 / p>

通过将图例置于图底部, ggplot 自动将图例标签置于值之间。

  library(ggplot2)

dat < - data.frame(x = 0:100 ,y = runif(101,0,10),z = seq(0,12,len = 101))

dat $ col < - cut(
dat $ z,
breaks = c(0,2,4,6,8,10,Inf),
labels = c(2,4,6,8,10, - >)


ggplot(dat,aes(x,y,col = col))+
geom_point(size = 10)+
sca le_colour_brewer(,palette =Greens)+
主题(legend.position =bottom)


I usually plot maps using GrADS, and usually I use a color legend that in the plot will look like this:

I would like to do the same using ggplot2 in R. If using simply:

g <- g + scale_fill_brewer(palette="Greens", na.value="NA", name=legendtitle)
#g is the previously saved plot with some simple options, prepared with cut()

The output is of course this:

So I'd like to be able to do two things:

  1. Shift the labels so they are between the colors, note indicating the interval above (note: renaming the labels is not the problem, shifting them is)
  2. Last label should be arrow-like, to indicate that entries above the maximum (10 in the example) are indicated in the darkest color (dark green in the example).

EDIT: Using help from the answer below, I've come to this:

Part 1. of my question is almost solved, even if it does not look perfect. I'd really like to get rid of the white space between the colors, any idea? Part 2... I have no idea whatsoever.

My code snippet uses:
theme(legend.position="bottom", legend.key.width = unit(1, "cm"), legend.key.height = unit(0.3, "cm")) + guides(fill=guide_legend(label.position = "bottom", label.hjust = 1.2))

解决方案

Here is something to get you started.

The idea is that you use cut() to create the cut points, but specify the labels in the way you desire.

By putting the legend at the bottom of the plot, ggplot automatically puts the legend labels "in between" the values.

library(ggplot2)

dat <- data.frame(x=0:100, y=runif(101, 0, 10), z=seq(0, 12, len=101))

dat$col <- cut(
  dat$z, 
  breaks=c(0, 2, 4, 6, 8, 10, Inf), 
  labels=c(2, 4, 6, 8, 10, "-->")
)

ggplot(dat, aes(x, y, col=col)) + 
  geom_point(size=10) + 
  scale_colour_brewer("", palette="Greens") +
  theme(legend.position="bottom")

这篇关于使用ggplot2生成带偏移标签的颜色图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆