Reputation: 349
I have this code to give the graph shown below:
d=ggplot(df, aes(x=Year, y=NAO_Index, width=.8)) +
+ geom_bar(stat="identity", aes(fill=NAO_Index>0), position='identity', col = 'transparent') +
+ theme_bw() + scale_fill_manual(values=c("royalblue", "firebrick3"), name="NAO Oscillation", labels=c("Negative", "Positive"), guide=guide_legend(reverse=TRUE)) +
theme(legend.position=c(0.06, 0.92)) +
+ theme(axis.title.x=element_text(vjust=-0.2)) +
+ geom_line(data=dfmoveav, aes(x=Year ,y=moveav)) +
+ ylab("NAO Index") +
+ ggtitle("NAO Index between 1860 and 2050") +
+ scale_x_continuous(breaks=c(seq(1860,2050,10))) +
+ scale_y_continuous(breaks=c(seq(-3.5,3.5,0.5)))
I am only really concerned with the last line. In the graph the y-axis only goes from -3 to 2.5. How do I get it from -3.5 to 3.5 so it is even?
I'm sure I am making a simple error but cannot figure it out!
Many thanks in advance.
Upvotes: 3
Views: 12809
Reputation: 5856
You are almost there. Try to set limits.
d=ggplot(df, aes(x=Year, y=NAO_Index, width=.8)) +
+ geom_bar(stat="identity", aes(fill=NAO_Index>0), position='identity', col = 'transparent') +
+ theme_bw() + scale_fill_manual(values=c("royalblue", "firebrick3"), name="NAO Oscillation", labels=c("Negative", "Positive"), guide=guide_legend(reverse=TRUE)) +
theme(legend.position=c(0.06, 0.92)) +
+ theme(axis.title.x=element_text(vjust=-0.2)) +
+ geom_line(data=dfmoveav, aes(x=Year ,y=moveav)) +
+ ylab("NAO Index") +
+ ggtitle("NAO Index between 1860 and 2050") +
+ scale_x_continuous(breaks=c(seq(1860,2050,10))) +
+ scale_y_continuous(breaks=c(seq(-3.5,3.5,0.5)), limits = c(-3.5, 3.5))
More about it here
To map line into the legend you should map the variable to aesthetic. But it's not trivial and you'll find references to avoid this approach.
df <- data.frame(year=factor(seq(1:10)),
nao = rnorm(10, 0, 2),
mov = rnorm(10, 0,3))
df2 <- data.frame(year=factor(seq(1:10)),
mov = df$nao+rnorm(10, 0, 0.1),
g = .1)
ggplot() +
geom_bar(data = df, aes(x=year, y=nao, fill=nao > 0), width=.8,
stat="identity", position ='identity', col = 'transparent') +
geom_line(data = df2, aes(x = year, y = mov, group = g, size = g)) +
scale_fill_manual(values=c("royalblue", "firebrick3"),
name="NAO Oscillation",
labels=c("Negative", "Positive"),
guide=guide_legend(reverse=TRUE)) +
scale_size('Trend', range = 1, labels = 'Moving\naverage') +
ggtitle("NAO Index between 1860 and 2050") +
scale_y_continuous(breaks=c(seq(-5,5,0.5)), limits = c(-5, 5)) +
ylab("NAO Index") +
theme(legend.position = c(0.07, 0.80),
axis.title.x = element_text(vjust= -0.2),
legend.background = element_blank())
This may not be the best approach to map variables to aesthetics.
Upvotes: 6