I am quite new to ggplot2 and it's been challenging to reproduce a similar chart in Excel. I almost got it to work, but now I need to figure out a way to make the geom_point/line's legend key (3rd item in the legend) to not show the box around it.
Note: I know there are answers to similar problem by using + theme(legend.key = element_blank())
, but it has no effect on the legend. I suspect it has something to do with the scale_*_manual
in the code. Any other solutions would be truly appreciated!
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'))