Search code examples
rggplot2vistime

Vertical vistime timeline and overlapping geom_text labels


I'm trying to draw a vertical timeline using vistime with its ggplot plotting option. My main intention is to better integrate it with text, side by side. This is the code:

library("vistime")
library("plotly")
data <- read.csv("../../data/programming.csv")
g <- gg_vistime(data, col.event="Item", col.start="Start.Date", col.end="End.Date", col.group="Group")
g + theme(axis.text.x = element_text(angle=90, color='blue4',size=14) )+coord_flip()

Image result

As you can see, as I'm doing the coord_flip, the labels intersect with each other. I'd like to make the labels go vertical. This is code that draws them:

https://github.com/shosaco/vistime/blob/372da36791cbdb7ad7d6841ed991e55b36f77e06/R/plot_ggplot.R#L83-L91

So that means that it's a geom_text sentence. Is there some way to change the orientation of geom_text-drawn text once it's done? Can I use some theme command to do that? Barring that, is there any way I can change the placement of the labels using vistime?


Solution

  • You can deconstruct any ggplot2 visualization with (surprisingly) ggplot_build (actually, what it does is to create elements that can be rendered using the plain vanilla plot).

    data <- read.csv("data/programming.csv")
    
    
    g <- gg_vistime(data, col.event="Item", col.start="Start.Date", col.end="End.Date", col.group="Group") + theme(axis.text.x = element_text(angle=90, color='blue4',size=14) )+coord_flip()
    
    g.d <- ggplot_build(g)
    
    g.d$data[[4]]$angle <- 90
    
    rebuilt <- ggplot_gtable(g.d)
    
    png(filename="img/timeline.png", width=240, height=960)
    plot(rebuilt)
    dev.off()
    

    That creates a data frame with different elements of the plot, including g.d$data which contains, effectively, the data and its properties when rendered in its 4th element. g.d$data[[4]]$angle contains the angle of all the geom_text elements that have been rendered. So once you get that, it's just a matter of changing it individually or colectively to what you want. You need to reconstruct the plot using ggplot_gtable and then use the core plot command to plot and render it any way you want, in this case a png.

    At any rate, ggplot_build allows you to introspect the data structures and different pieces of the graph created using ggplot, changing any one of its layers, metadata or pieces after they have been created. In our case, it produces the intended effect