Reputation: 529
I've been having a nightmare sorting a legend problem for a while now where when doing a geom_point
with a geom_smooth
I end up with two distinct legends on my plot and try as I might I cannot work out how to combine them into something more usable.
The plot code is...
require(ggplot2)
require(scales)
require(cowplot)
palette <- scales::hue_pal()(3)
ggplot(df.Overview, aes(x=datePublished, y=sentiment, colour = type, group=type, linetype = type)) +
geom_point(aes(shape=factor(type)), size=3.5, position=position_jitter(width=0.3), alpha = 0.5) +
geom_smooth(fullrange = TRUE, alpha = .25, show_guide = TRUE) +
scale_x_date(breaks = "1 week", labels=date_format("%b-%d"), limits = c(overviewStartDate,overviewEndDate)) + # limit plot to overview dates
scale_y_continuous(limits =c(-1,1), oob=squish) + # set upper and lower bounds of Y axis
theme_bw() +
background_grid(major = "xy", minor = "none") +
labs(x = "", y = "Sentiment Index") +
scale_colour_manual( values = palette,
name="GSE",
breaks=c("sentiment_TitleDescMean", "sentiment_body"),
labels = c("x\u0304 (Title & Desc)", "Body") ) +
scale_shape_manual( values = c('sentiment_TitleDescMean' = 17, 'sentiment_body'= 15),
name="Story Part ",
breaks=c("sentiment_TitleDescMean", "sentiment_body"),
labels = c("x\u0304 (Title & Desc)", "Body") ) +
scale_linetype_discrete(name="GSE",
breaks=c("sentiment_TitleDescMean", "sentiment_body"),
labels = c("x\u0304 (Title & Desc)", "Body") ) +
theme(legend.key=element_rect(fill='white'), legend.position=c(.05,.75), legend.background = element_rect(fill="white", size=0.5, linetype="solid", colour ="grey30")) # set legend position
Which results in the following plot...
What I really want...
legend.position
parameters each time the plot changes.Can anyone help out with what I suspect is sorting the scale_
parts
Upvotes: 3
Views: 503
Reputation: 529
Heroka's comment had the answer for the primary question of how to combine the legends neatly. Super simple... change the call to scale
so that name="xxx"
is the same for each one.
Thusly...
scale_colour_manual( values = palette,
name="Story Part",
breaks=c("sentiment_TitleDescMean", "sentiment_body"),
labels = c("x\u0304 (Title & Desc)", "Body") ) +
scale_shape_manual( values = c('sentiment_TitleDescMean' = 17, 'sentiment_body'= 15),
name="Story Part",
breaks=c("sentiment_TitleDescMean", "sentiment_body"),
labels = c("x\u0304 (Title & Desc)", "Body") ) +
scale_linetype_discrete(name="Story Part",
breaks=c("sentiment_TitleDescMean", "sentiment_body"),
labels = c("x\u0304 (Title & Desc)", "Body") )
Upvotes: 2