1

I need to display in just one graphic the contrast between allocated budget, spent budget (these two shown in bars) and the execution percentage (shown as a line) of Public Expenditure in Education.

I have managed to display correctly the graphs I need on separated ways, in other words, my bars graph is ready and my line graph too. However, the data for each of these graphics belongs to different dataframes, so I got problems when trying to merge both of them in just one. Also, I need the y-axis of the line graphic to be secondary.

#Education Budget Stages
Years <- c("2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018") 
Allocated <- c(2769.56, 3049.32, 3447.86, 3858.57, 4333.35, 5173.91, 5294.66, 5030.17, 4928.42, 5152.78, 5288.91)
Spent <- c(1911.31, 2817.23, 3049.02, 3567.99, 3867.27, 4666.91, 4792.20, 4525.44, 4360.03, 4812.47, 4970.93)
Execution <- c(69.01, 92.39, 88.43, 92.47, 89.24, 90.2, 90.51, 89.97, 88.47, 93.4, 93.99)
df <- data.frame(Years, Allocated, Spent)
dfa <- data.frame(Years, Execution)
require(tidyr)
df.long <- gather(df, Budget_Stages, Values, -Years)

library(ggplot2)
#Evolution of Allocated and Spent Budget in Education
ged<- ggplot(data = df.long, aes(x = Years, y = Values, fill = Budget_Stages)) +
  coord_cartesian(ylim=c(1500,5500)) +
  theme_bw() +
  geom_col(width= 0.8, colour="black", position = position_dodge(width=0.7)) +
  scale_fill_manual(values=c("#F5B498", "#CECECE")) +
  guides(fill=guide_legend(""))

library(grid)
library(ggrepel)  

ged1 <- ged +
  theme(legend.position= c(0.5,-0.3), legend.direction = "horizontal") +
  theme(plot.margin = unit(c(1.5,2,1.5,2),"cm"))


#Execution of Public Expenditure in Education
ge2 <- ggplot(data=dfa, aes(x=Years, y=Execution, group=1)) +
  geom_line(size=0.5, aes(color="Execution")) +
  scale_y_continuous(sec.axis = dup_axis()) +  geom_line(linetype="solid", color="yellow") +
  geom_point(color="yellow")

print(ged1 + ged2 labs(x="", y=""))

I expect to see just one graphic including all the information I need, nevertheless R shows there's an aesthetic error.

aosmith
  • 34,856
  • 9
  • 84
  • 118
  • 1
    I believe this is because `ggplot2` is designed to not allow for multiple axes containing different data. See [these](https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) [discussions](https://stackoverflow.com/questions/49185583/two-y-axes-with-different-scales-for-two-datasets-in-ggplot2). – heds1 Jun 24 '19 at 22:27

0 Answers0