我是ggplot2的新手,在Excel中重现类似的图表一直很有挑战性.我几乎得到它的工作,但现在我需要找出一种方法来使geom_point/line的图例键(图例中的第3项)不显示它周围的框.
注意:我知道使用有类似问题的答案+ theme(legend.key = element_blank()),但它对图例没有影响.我怀疑它与scale_*_manual代码中的内容有关.任何其他解决方案将真正感激!
test <- data.frame(
group = 1:5,
cnt = rep(600, 5),
pct_cnt = rep(0.2, 5),
prem = c(12000000, 9800000, 8700000, 11000000, 3500000),
pct_prem = c(0.266666667, 0.217777778, 0.193333333, 0.244444444,
0.077777778),
relativity = c(1.5, 1.2, 1, 0.8, 0.4)
)
theme_set(theme_minimal())
normalizer <- round(max(test$relativity) / max(test$pct_prem), 0)
ggplot(test, aes(x = group)) +
geom_bar(aes(y = pct_prem, fill = 'prem', color = 'prem'), stat = 'identity', position = position_nudge(x = -0.1), width = 0.2) +
geom_bar(aes(y = pct_cnt, fill = 'cnt', color = 'cnt'), stat = 'identity', position = position_nudge(x = 0.1), width = 0.2) +
geom_point(aes(y = relativity / normalizer, color = 'rel', fill = 'rel'), size = 5) +
geom_line(aes(y = relativity / normalizer, color = 'rel'), size = 2) +
scale_color_manual(name = 'metric', values = c('prem' = NA, 'cnt' = NA, 'rel' = 'skyblue'),
labels = c('prem' = '%Prem', 'cnt' = '%Count', 'rel' = 'LRR')) +
scale_fill_manual(name = 'metric', values = c('prem' = 'orange', 'cnt' = 'dark green', 'rel' = NA),
labels = c('prem' = '%Prem', 'cnt' = '%Count', 'rel' = 'LRR')) +
scale_y_continuous(limits = c(0, 0.4), sec.axis = sec_axis(~.*normalizer, breaks = seq(0, 0.4, 0.1) * normalizer, name = 'relativity'))
Run Code Online (Sandbox Code Playgroud)
我不确定是否有使用just的方法ggplot,因为当使用常用override.aes修复时,框的颜色和图例键的颜色本身会同时改变.进入gtable,你可以这样做(在你的情节分配后p):
library(grid)
grb <- ggplotGrob(p)
#get the index of the legend-grob and store grob as leg
leg_index <- grep("guide-box", sapply(grb$grobs, function(x) x$name))
leg <- grb$grobs[[leg_index]]
Run Code Online (Sandbox Code Playgroud)
然后,你想看看传说中的gtable.要更改的关键bg是最后一个,因此请在底部查看rect背景.即,在这里
13 13 (6-6,2-2) key-5-1-bg zeroGrob[legend.key..zeroGrob.3081]
14 14 (6-6,2-2) key-5-1-1 rect[GRID.rect.3082]
15 15 (6-6,2-2) key-5-1-2 rect[GRID.rect.3083]
16 16 (6-6,2-2) key-5-1-3 points[GRID.points.3084]
17 17 (6-6,2-2) key-5-1-4 segments[GRID.segments.3085]
Run Code Online (Sandbox Code Playgroud)
索引14和15是属于最后一个键的索引.要确保删除bg,只需更改它们的图形参数即可.然后用更改的图例替换旧图例.
leg$grobs[[1]]$grobs[[14]]$gp$col <- "white"
leg$grobs[[1]]$grobs[[15]]$gp$col <- "white"
grb$grobs[[leg_index]] <- leg
grid.newpage()
grid.draw(grb)
Run Code Online (Sandbox Code Playgroud)