Reputation: 111
I would like to change the legend order to q1, median, q3 in my bar graph as now medium is named first which is not really logical.
barmedium <- ggplot(data=medium, aes(x=year, y=budgetresidual, group=Legend)) +
geom_line(aes(linetype=Legend))+
geom_point() +
scale_linetype_manual(values=c("solid", "longdash", "dotted")) +
scale_x_continuous(breaks = round(seq(min(medium$year), max(medium$year), by = 1),1),) +
scale_y_continuous(breaks =c(-15,-10,-5,0,5,10), limits = c(-16,10)) +
labs( x = "Year", y = "Budget residual") + theme_bw()
barmedium <- barmedium + theme_update(legend.position='top')
barmedium
medium<- data.frame(
stringsAsFactors = FALSE,
year = c(2012L,2012L,2012L,2013L,2013L,2013L,
2014L,2014L,2014L,2015L,2015L,2015L,2016L,
2016L,2016L,2017L,2017L,2017L,2018L,
2018L,2018L,2019L,2019L,2019L),
Legend = c("q1","median","q3","q1","median","q3",
"q1","median","q3","q1","median","q3",
"q1","median","q3","q1","median","q3",
"q1","median","q3","q1","median","q3"),
budgetresidual = c(-8,-1,4,-9,-4,3,
-15,-9,1,-9,-3,
3,-12,-5,-0,-10,
-7,-2,0.2,3,8,-1,
3,6)
)
Created on 2020-07-01 by the reprex package (v0.3.0)
Upvotes: 2
Views: 33
Reputation: 4480
Try casting the Legend column into a factor reordering categories as you wish:
medium<- data.frame(
stringsAsFactors = FALSE,
year = c(2012L,2012L,2012L,2013L,2013L,2013L,
2014L,2014L,2014L,2015L,2015L,2015L,2016L,
2016L,2016L,2017L,2017L,2017L,2018L,
2018L,2018L,2019L,2019L,2019L),
Legend = c("q1","median","q3","q1","median","q3",
"q1","median","q3","q1","median","q3",
"q1","median","q3","q1","median","q3",
"q1","median","q3","q1","median","q3"),
budgetresidual = c(-8,-1,4,-9,-4,3,
-15,-9,1,-9,-3,
3,-12,-5,-0,-10,
-7,-2,0.2,3,8,-1,
3,6)
)
medium$Legend <- factor(medium$Legend, levels = c("q1", "median", "q3"))
barmedium <- ggplot(data=medium, aes(x=year, y=budgetresidual, group=Legend)) +
geom_line(aes(linetype=Legend))+
geom_point() +
scale_linetype_manual(values=c("solid", "longdash", "dotted")) +
scale_x_continuous(breaks = round(seq(min(medium$year), max(medium$year), by = 1),1),) +
scale_y_continuous(breaks =c(-15,-10,-5,0,5,10), limits = c(-16,10)) +
labs( x = "Year", y = "Budget residual") + theme_bw()
barmedium <- barmedium + theme_update(legend.position='top')
barmedium
Upvotes: 1