R: RStudio: How to get silhouette plot working?

user32259 picture user32259 · Mar 4, 2013 · Viewed 15.3k times · Source

Today I have realised that the silhouette plot in the cluster package doesn't display properly in RStudio. A Google search revealed that someone else had had a problem with this:

http://support.rstudio.org/help/discussions/problems/3094-plotsnot-showing-up-in-r-studio

Being new to R, it was unclear to me whether the problem had been resolved in this thread! So my question is: is there a way to get the silhouette plot to display properly in RStudio?

Thanks for any help.

Example script:

library(cluster)
data(xclara)
km <- kmeans(xclara,3)
dissE <- daisy(xclara)
sk <- silhouette(km$cl, dissE)
plot(sk)

Answer

Carl Witthoft picture Carl Witthoft · Mar 4, 2013

Seems like the thread you reference was pretty explicit: the silhouette package may have a bug wrt png output, and RStudio doesn't play nice with some other graphics formats. So you need to specify, as Josh wrote, "The pdf(), quartz(), and windows() devices..." when using RStudio.

Edit: so what you need to do is

pdf('my_nice_plot.pdf')
plot(sk)
dev.off()

Which writes your plot directly to the file. You might try replacing the first line with png('my_nice_plot.png') and so on, as those should work as well. But I doubt you'll get a clean plot in RStudio's graphics window until they upgrade their interface.