asachet
asachet

Reputation: 6921

Disable plot display in R

I am trying to turn off the display of plot in R.

I read Disable GUI, graphics devices in R but the only solution given is to write the plot to a file.

What if I don't want to pollute the workspace and what if I don't have write permission ? I tried options(device=NULL) but it didn't work.

The context is the package NbClust : I want what NbClust() returns but I do not want to display the plot it does.

Thanks in advance !

edit : Here is a reproducible example using data from the rattle package :)

data(wine, package="rattle")
df <- scale (wine[-1])

library(NbClust)

# This produces a graph output which I don't want
nc <- NbClust(df, min.nc=2, max.nc=15, method="kmeans")

# This is the plot I want ;)
barplot(table(nc$Best.n[1,]), 
    xlab="Numer of Clusters", ylab="Number of Criteria",
    main="Number of Clusters Chosen by 26 Criteria")

Upvotes: 4

Views: 9899

Answers (2)

Brian Diggs
Brian Diggs

Reputation: 58875

You can wrap the call in

pdf(file = NULL)

and

dev.off()

This sends all the output to a null file which effectively hides it.

Upvotes: 10

Spacedman
Spacedman

Reputation: 94317

Luckily it seems that NbClust is one giant messy function with some other functions in it and lots of icky looking code. The plotting is done in one of two places.

Create a copy of NbClust:

> MyNbClust = NbClust

and then edit this function. Change the header to:

MyNbClust <-
    function (data, diss = "NULL", distance = "euclidean", min.nc = 2, 
              max.nc = 15, method = "ward", index = "all", alphaBeale = 0.1, plotetc=FALSE) 
{

and then wrap the plotting code in if blocks. Around line 1588:

    if(plotetc){
        par(mfrow = c(1, 2))
        [etc]
        cat(paste(...
    }

and similarly around line 1610. Save. Now use:

 nc = MyNbClust(...etc....)

and you see no plots unless you add plotetc=TRUE.

Then ask the devs to include your patch.

Upvotes: 4

Related Questions