Search code examples
rplotggplot2axis-labelsgeom-bar

Add second y-axis without corresponding x-data


I'm making a graphical analysis of the course evaluations. I got the following data:

> str(dataJ2)
'data.frame':   16 obs. of  22 variables:
...
 $ lk_nummer           : Factor w/ 111 levels "051-0311-00S",..: 19 30 38 47 49 50 51 55 56 59 ...
 $ le_titel            : Factor w/ 111 levels "","Advanced Methods and Strategies in Synthesis",..: 6 99 75 82 84 8 40 39 38 68 ...
 $ anzahl_stud         : int  7 79 1 34 10 20 83 10 4 11 ...
 $ durchschnitt        : num  4.61 5.35 3.5 4.4 4.4 4.33 4.49 4.53 5.38 4.48 ...
 $ standardabweich     : num  0.4 0.54 0 1.02 1.21 0.62 1.17 0.9 0.28 0.68 ...
...
 $ prozent_best        : num  85.7 97.5 0 70.6 90 80 73.5 90 100 81.8 ...
...

Using ggplot2 I was able to make a plot looking like this:

plotJ2 <- ggplot(dataJ2, aes(y=durchschnitt,x=le_titel)) 

plotJ2 + geom_bar(position=position_dodge(), stat="identity", fill = I("chartreuse4")) + 
  scale_y_continuous(limits=c(0,6.6),breaks=seq(from=1, to=6, by=1)) +
  geom_errorbar(aes(ymin=durchschnitt-standardabweich, ymax=durchschnitt+standardabweich), width=.1) +
  ggtitle("2. Jahr Bsc Biologie") +
  ylab("Durchschnitt") + xlab("Fächer") +
  geom_text(aes(label = durchschnitt, y = 1.8), size = 4, colour="gray85") + 
  geom_text(aes(label = anzahl_stud, y = 0.2), size = 4, colour="grey85") + 
  geom_text(aes(label = prozent_best, y = 6.55), size = 4, colour="chartreuse4", adj=1) +
  geom_text(aes(label = "%", y = 6.6), size = 4, colour="chartreuse4", adj=0) +
coord_flip() 

Which looks like this when plotted.

But however, the "prozent_best" in the graphical part looks not very nice. I tried to add with mtext, text and facet_wrap the data from "dataJ2$prozent_best" as a second y-axis label on the right side of the gray graph part but couldn't make it work.

Any recommendations?

Useful translations/descriptions of the data annotation:

lk_nummer -> number of the lectures

le_titel -> name of the lectures

anzahl_stud -> number of students

durchschnitt -> average

prozent_best -> number of students which passed the exam in percent

Fächer -> classes


Solution

  • Try:

     geom_text(aes(label = paste0(prozent_best,'%'), y = 6.55),
     size = 4, colour="chartreuse4", hjust='right')
    

    That will combine the '%' symbol with the value into one string. Generally I would suggest generating your label vectors outside the ggplot call, but for this it does not add too much mess.

    Also, you might want to look into adding scale_x_continuous(expand=0,limits=c(0,7)). That will get rid of the ugly grey bar on the left side.

    Possibly also try adding in theme_bw() since your plot is already so busy the grey blocks in the background of ggplots standard theme just make it look mushy.