Search code examples
rchord-diagramcirclize

How to Save Circlize Chord Diagram as a graphic object


I created a chord diagram in R using the circlize package. I noticed that this graphic is not being saved as a ggplot object. I am trying to make the graphic an object so I can export it to excel. Any suggestions?

chordDiagram(as.data.frame(ba_delivery_flow.sas7bdat), annotationTrack = "grid", preAllocateTracks =  1,
                        direction.type = "diffHeight")
circos.trackPlotRegion(track.index = 2, panel.fun = function(x, y) {
xlim = get.cell.meta.data("xlim")
ylim = get.cell.meta.data("ylim")
sector.name = get.cell.meta.data("sector.index")
circos.text(mean(xlim), ylim[1]+5, sector.name, facing = "clockwise", niceFacing = TRUE, adj = c(0, .5), cex = 1)
circos.axis(h = "top", labels.facing = "clockwise", labels.cex = 0.5, major.tick.percentage = 0.2, sector.index = sector.name, track.index = 2)

}, bg.border = NA)

Solution

  • R has two graphics systems, base and grid. (grid is what ggplot2 and lattice are built on.) Your plot is built with base, and unfortunately base plots are not objects R, so you cannot assign them to a variable, and saving them is a little different.

    To save the plot in a file, you open up a graphics device, like png, put your code to draw the plot, and then use dev.off() to close the device. Like this:

    png("my_plot.png") 
    
    ## all of your plotting code
    
    dev.off()
    

    See ?png an argument list, and a few other devices too.


    As an aside, you can save ggplots this way too. If you have a plot object p, you can put print(p) in between the png() and the dev.off(). This is essentially what ggsave does internally.