【问题标题】:ggplot2: Use every N-th legend key labelggplot2:使用每 N 个图例键标签
【发布时间】:2013-02-27 04:29:34
【问题描述】:

我有一个包含 72 个离散类别的 data.frame。当我按这些类别着色时,我会在图例中得到 72 个不同的键。我宁愿只使用第二个或第三个键。

知道如何减少图例中的行数吗?

谢谢 H.

下面给出了重现我的问题的代码。

t=seq(0,2*pi,length.out=10)
RR=rep(cos(t),72)+0.1*rnorm(720)
dim(RR)=c(10,72)
stuff=data.frame(alt,RR)
names(stuff)=c("altitude",
               paste(rep(15:20,each=12),
               rep(c("00","05",as.character(seq(from=10,to=55,by=5))),6),
               sep=":"))

bb=melt(stuff,id.vars=c(1))
names(bb)[2:3]=c("period","velocity")
ggplot(data=bb,aes(altitude,velocity))+geom_point(aes(color=period))+geom_smooth()

【问题讨论】:

  • 您想排除某些类别还是将它们合并在一起?

标签: r ggplot2 legend


【解决方案1】:

您可以将period 值视为geom_point() 中的数字。这将使颜色成为渐变(从 1 到 72 的值对应于级别数)。然后使用scale_colour_gradient(),您可以设置所需的休息次数并添加标签作为您的实际期间值。

ggplot(data=bb,aes(altitude,velocity))+
  geom_point(aes(color=as.numeric(period)))+
  geom_smooth()+
  scale_colour_gradient("Period",low="red", high="blue",
          breaks=c(seq(1,72,12),72),labels=unique(bb$period)[c(seq(1,72,12),72)])

【讨论】:

    【解决方案2】:

    在这里为discrete_color_scale自定义图例看起来很难!所以我提出了一个点阵解决方案。您只需为 auto.key 列表提供正确的文本。

    libarry(latticeExtra)
    labels.time <- unique(bb$period)[rep(c(F,F,T),each=3)] ## recycling here to get third label
     g <- xyplot(velocity~altitude, data=bb,groups=period,
           auto.key=list(text=as.character(labels.time),
                         columns=length(labels.time)/3),
           par.settings = ggplot2like(),   axis = axis.grid,
           panel = function(x,y,...){
             panel.xyplot(x,y,...)
             panel.smoother(x,y,...)
           })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      相关资源
      最近更新 更多