ggplot2:如何减少图例

时间:2015-11-18 02:48:16

标签: r ggplot2

我有以下功能:

gg.barplots <- function(inp, order, xlab.strg, ylab.strg) {
  require(RColorBrewer)
  require(ggplot2)
  require(reshape2)
  arg <- c(expression(hat(p)[M]), expression(hat(p)[C]))
  p <- order
  col <- c(colorRampPalette(brewer.pal(9,'Blues')[2:9])(p+2), 
           colorRampPalette(brewer.pal(9,'Oranges')[2:9])(p+2))
  lab <- c(0:p, paste(">",p,sep=""))
  freq.mat <- data.frame(labels = lab, inp)
  names(freq.mat) <- c("x", "Magnitude-only", "Complex-valued")
  freq.mat$x <- factor(freq.mat$x, levels = c(levels(freq.mat$x)[-1],levels(freq.mat$x)[1]))
  ## force the orders to be as we want them to appear, using the factor function with levels specified. 
  freq.df <- melt(data = freq.mat, id.vars = 1, measure.vars = 2:3)
  fill.vars <- paste(rep(names(freq.mat)[-1], times = p), rep(freq.mat$x, each = 2), sep = ":")
  fill.vars <- factor(fill.vars, levels = fill.vars)
  freq.df <- data.frame(fill.vars, freq.df[rep(c(0,p+2), times = p + 2) + rep(1:(p + 2), each = 2), ])
  ggplot(data=freq.df, aes(x = x, y = value, fill = fill.vars)) +
    geom_bar(stat="identity", position=position_dodge(), colour = "black") +
    scale_fill_manual(values = col[rep(c(0,p+2), times = p + 2) + rep(1:(p + 2), each = 2)]) +
    theme_bw() +
    xlab(arg) +
    ylab(ylab.strg) +
    xlab(xlab.strg) +
    ylab(ylab.strg)
}

给出了以下(两个躲避的条形图),如下例所示:

dput(out.AR2$AR.rate)
structure(c(0.25178, 0.06735, 0.64564, 0.03523, 0.04396, 0.0027, 
0.90415, 0.04919), .Dim = c(4L, 2L), .Dimnames = list(c("0", 
"1", "2", ">2"), NULL))

并调用函数:

gg.barplots(inp = out.AR2$AR.rate, order = 2, xlab.strg = "AR order", ylab.strg = "Proportions")

导致下图:

enter image description here

现在我觉得(甚至忽略了这个情节中当前传说的内在丑陋),整个传说都没有必要。我认为应该只有颜色(比如橘子音阶的中间值和蓝调音阶的中间值)应该足以代表情节的重要部分。其余部分(图例中的AR订单)已经在图中。

我的问题:我如何制作一个只有这两种颜色(以及与之相关的单词Complex-value和Magnitude)的图例?我已经尝试了几件事,我有点迷茫,抱歉。

1 个答案:

答案 0 :(得分:1)

你的功能有点乱 - 你可以将它分成两个功能,一个用于清理,另一个用于绘图。

无论如何,获得所需内容的最简单方法是使用var tabIdToPreviousUrl = {}; chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){ if (changeInfo.url && changeInfo.url.match(/<regex>/g)) { var previousUrl = ""; if (tabId in tab) { previousUrl = tabIdToPreviousUrl[tabId]; } // If the domain is different perform action. if (previousUrl !== changeInfo.url) { // do something } // Add the current url as previous url tabIdToPreviousUrl[tabId] = changeInfo.url; } }); 参数breaks。这允许您仅选择图例中所需的级别:

scale_fill_manual

enter image description here