R igraph output vertice is not shown - r

I am using R igraph package to display gene networks. The plot on Rstudio is like this (I can't post image because I am new user and don't have enough reputation, sorry about that):
R igraph on preview
Now I want to draw this on file to clearly see the changes and there is always an issue on vertices near margin side like this:
part of output pdf file
My code is as follows`
pdf("graph.pdf",width = 20, height = 10)
par(mar = c(9,9,9,9))
plot(finalnet, edge.arrow.size=0.1, edge.curved=FALSE,vertex.size= 3, margin = -0.5)
dev.off()
Update: I have tried square layout and the problem persists, here is my plotting object and square plot.
square plot
rda file for my igraph object
Can anyone give me an suggestion how to solve this issue? To whole net is about 170 vertices but I don't know why it cannot be displayed on output file well. I have tried different plot options in mai, mar but this seems to fail.

The reason you are getting this behavior is because you are specifying margin in your plot call. margin=-0.5 is telling R to extend the plot 0.5 units past the graphics device dimensions, below are three examples:
Your original plotting call, notice the clipping
pdf("withMargin.pdf")
par(mar=c(9,9,9,9))
plot(g, margin=-0.5)
dev.off()
Without the call to par, problem still presists but now youuse the entire dimension of the graphics device.
png("withoutPar_Margin.png")
#par(mar=c(9,9,9,9))
plot(g, margin=-0.5)
dev.off()
Lastly, removing the margin in plot
png("withoutplotMargin.png")
par(mar=c(9,9,9,9))
plot(g)
dev.off()

You're specifying a rectangular size for what looks like a square object. Try a square size, as in
pdf("graph.pdf")
This will use the defaults, which are square.
But, it's hard to know for sure since you haven't given us the object to troubleshoot for you.

Related

R partykit::ctree offset labels on edges

I am working with ctree and my data set has a covariate of factors that create a node. There are enough factors for that covariate and their names are long enough that they overlap on each other in the edges created at the node. I want to find a way to stop this overlap.
I checked other questions and found one answer that supplies some help. The plot for ctree relies on the grid package and I can use functions to write new labels on the edge. My problem now is that I don't know how to suppress the labels that are printed as default when I plot the tree. I don't know enough about grid or plot.party to figure out which object needs to be suppressed.
An example of my problem in the following image:
Code for my example problem:
libary(partykit)
library(tidyverse) #this is here for the mpg data set in next line. not required for partykit
data(mpg)
irt <- ctree(hwy~as.factor(class),data=mpg)
plot(irt)
The resulting 1st node has one edge with "2seater, compact, midsize, subcompact" and the other edge with "minivan, pickup, suv". What I end up seeing in the plot is "2seater, compact, midsize, subcompaminivan, pickup, sub". I've already made the graphics device full screen. (I have other trees that only have one node and so that makes those look odd at the full screen dimension, so I don't want to go back and forth.)
The partial solution I have is
plot(irt, pop=FALSE)
seekViewport("edge1-1")
grid.text("2seater, compact,\n midsize, subcompact")
This stacks "2seater, compact" on top of "midsize, subcompact" and would keep them from overlapping "minivan, pickup, suv". But now, I have the original too-long label still in the plot. And the edge that the label I'm trying fix is attached to has a break in a place that doesn't work with the new stacked label. It would be nice to fix that edge, but the real problem is suppressing the original, too-long label on edge1-1.
The edge labels are drawn by the function edge_simple() which offers various kinds of justifications for the edge labels, see ?edge_simple. The justification is only applied if the edge labels are on average longer than justmin, defaulting to Inf (i.e.: no justification). Various justifications are possible (alternating, increasing, decreasing, or equal).
Thus, in your case the simplest solution is probably to set justmin to a small enough finite value. Alternatively (or additionally) you could also decrease the font size by setting gpar(fontsize = ...). For illustration both examples below have been generated on a 6in x 8in PNG device:
library("partykit")
data("mpg", package = "ggplot2")
irt <- ctree(hwy ~ factor(class), data = mpg)
plot(irt, ep_args = list(justmin = 15))
plot(irt, ep_args = list(justmin = 15), gp = gpar(fontsize = 10))

plot igraph in a big area

Just wondering if it is possible to increase the size of the plot so that the nodes and edges can be more scattered over the plot.
Original plot:
What are expected:
I tried many parameters in the layout function such as area, niter, and so on, but all of them do not work. By the way, I am using 'igraph' package in R.
If you are referring to the actual size of the produced output (pdf, png, etc), you can configure it with the width and height parameters. Check this link for png,bpm, etc, and this link for PDF format.
A MWE is something like this:
png("mygraph.png", heigh=400, width=600)
#functions to plot your graph
dev.off()
If you are referring to the size of the graphic produced by the layout function, as #MrFlick referred, you should check the parameters of the particular layout you are using.
Hope it helps you.
In your second graph, it's obviously the graph can be divided into several clusters (or sections). If I understood you correctly, you want to have a layout that separates your clusters more visibly.
Then you can draw this by calculating a two-level layout:
First, calculate the layout of the graph in order to find a place for each cluster.
Second, calculate the layout in each cluster according to first step and plot nodes in the corresponding place.

Formatting Issue with barchart() of Cluster Analysis

I've created a segment profile plot of my cluster analysis but I'm having an issue with the formatting of a barchart() command. Here is the chart I created. The obvious issue is that my lines are too close together to read.
Here you can see the code I used to create this chart. Can someone tell me what to add in order to make this chart readable? Below is an example of my code used.
R code for reproducing the clustering and PCA we used:
## if not installed, install: install.packages("flexclust")
library("flexclust")
load("vacpref.RData")
cl6 <- kcca(vacpref, k=vacpref6, control=list(iter=0),
simple=FALSE, save.data=TRUE)
summary(cl6)
hierarchical clustering of the variables
varhier <- hclust(dist(t(vacpref)), "ward")
par(mar=c(0,0,0,15))
plot(as.dendrogram(varhier), xlab="", horiz=TRUE,yaxt="n")
principal component projection
vacpca <- prcomp(vacpref)
R code for generating the Segment Separation Plot
pairs(cl6, project=vacpca, which=1:3, asp=TRUE,points=FALSE,
hull.args=list(density=10))
R code for generating the Segment Positioning Plot:
col <- flxColors(1:6)
col[c(1,3)] <- flxColors(1:4, "light")[c(1,3)]
par(mar=rep(0,4))
plot(cl6, project=vacpca, which=2:3,
col=col,asp=TRUE,points=F,hull.args=list(density=10),axes=FALSE)
projAxes(vacpca, minradius=.5, which=2:3, lwd=2, col=”darkblue”)
R code for generating the Segment Profile Plot:
barchart(cl6, shade=TRUE, which=rev(varhier$order),legend=TRUE)
The last command was the one I used to create my segment profile plot but I wasn't sure if the commands before may have affected it in any way. I'm new to R.
One trick I often use is to change the width/height and resolution through exporting the image. Try this:
png("c:\\temp\\myCrazyPlot.png", res=250, height=8, width=12, unit="in")
barchart(cl6, shade=TRUE, which=rev(varhier$order),legend=TRUE)
# And whatever other plot commands for the same plot
dev.off()
Then go check your .png file. By tinkering the height and width, you can somehow adjust the spacing of the labels at the y-axis. You may even make its height longer than its width to let the labels spread out. (I think currently you can't do that because that's the maximal height of your screen?)

Error in plot.new() : figure margins too large in R

I'm new to R but I've made numerous correlation plots with smaller data sets. However, when I try to plot a large dataset (2gb+), I can produce the plot just fine, but the legend doesn't show up. Any advice? or alternatives?
library(gplots)
r.cor <- cor(r)
layout(matrix(c(1,1,1,1,1,1,1,1,2,2), 5, 2, byrow = TRUE))
par(oma=c(5,7,1,1))
cx <- rev(colorpanel(25,"yellow","black","blue"))
leg <- seq(min(r.cor,na.rm=T),max(r.cor,na.rm=T),length=10)
image(r.cor,main="Correlation plot Normal/Tumor data",axes=F,col=cx)
axis(1, at=seq(0,1,length=ncol(r.cor)), labels=dimnames(r.cor)[[2]],
cex.axis=0.9,las=2)
axis(2,at=seq(0,1,length=ncol(r.cor)), labels=dimnames(r.cor)[[2]],
cex.axis=0.9,las=2)
image(as.matrix(leg),col=cx,axes=T)
Error in plot.new() : figure margins too large
tmp <- round(leg,2)
axis(1,at=seq(0,1,length=length(leg)), labels=tmp,cex.axis=1)
This error can occur in Rstudio simply because your "Plots" pane is just barely too small. Try zooming your "Files, Plots, Packages, Help, Viewer" and see if it helps!
The problem is that the small figure region 2 created by your layout() call is not sufficiently large enough to contain just the default margins, let alone a plot.
More generally, you get this error if the size of the plotting region on the device is not large enough to actually do any plotting. For the OP's case the issue was having too small a plotting device to contain all the subplots and their margins and leave a large enough plotting region to draw in.
RStudio users can encounter this error if the Plot tab is too small to leave enough room to contain the margins, plotting region etc. This is because the physical size of that pane is the size of the graphics device. These are not independent issues; the plot pane in RStudio is just another plotting device, like png(), pdf(), windows(), and X11().
Solutions include:
reducing the size of the margins; this might help especially if you are trying, as in the case of the OP, to draw several plots on the same device.
increasing the physical dimensions of the device, either in the call to the device (e.g. png(), pdf(), etc) or by resizing the window / pane containing the device
reducing the size of text on the plot as that can control the size of margins etc.
Reduce the size of the margins
Before the line causing the problem try:
par(mar = rep(2, 4))
then plot the second image
image(as.matrix(leg),col=cx,axes=T)
You'll need to play around with the size of the margins on the par() call I show to get this right.
Increase the size of the device
You may also need to increase the size of the actual device onto which you are plotting.
A final tip, save the par() defaults before changing them, so change your existing par() call to:
op <- par(oma=c(5,7,1,1))
then at the end of plotting do
par(op)
If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and trying plot() again may work.
This sometimes happen in RStudio. In order to solve it you can attempt to plot to an external window (Windows-only):
windows() ## create window to plot your file
## ... your plotting code here ...
dev.off()
I got this error in R Studio, and was simply fixed by making the sidebar bigger by clicking and dragging on its edge from right to left.
Picture here: https://janac.medium.com/error-in-plot-new-figure-margins-too-large-in-r-214621b4b2af
Check if your object is a list or a vector. To do this, type is.list(yourobject). If this is true, try renaming it x<-unlist(yourobject). This will make it into a vector you can plot.
Just zoom this area if you use RStudio.
I found this error today. Initially, I was trying to output it to a .jpeg file with low width and height.
jpeg("method1_test.jpg", width=900, height=900, res=40)
Later I increased the width and height to:
jpeg("method1_test.jpg", width=1900, height=1900, res=40)
The error was not there. :)
You can also play with the resolution, if the resolution is high, you need more width and height.
I had this error when I was trying to plot high dimensional data. If that's what is going on with you, try multidimensional scaling: http://www.statmethods.net/advstats/mds.html
I struggled with this error for weeks (using RStudio). I tried moving the plot window bigger and smaller, but that did not consistently help. When I moved (dragged) the application to my bigger monitor, the problem disappeared! I was stunned... so many wasted hours... I knew my code was correct...
If margin is low, then it is always better to start with new plotting device:
dev.new()
# plot()
# save your plot
dev.off()
You will never get margin error, unless you plot something large which can not be accommodated.
RStudio Plots canvas is limiting the plot width and heights. However if you make your plot from Rmarkdown code chunk, it works without canvas field limitation because plotting area set according to the paper size.
For instance:
```{r}
#inside of code chunk in Rmarkdown
grid <- par(mfrow=c(4, 5))
plot(faithful, main="Faithful eruptions")
plot(large.islands, main="Islands", ylab="Area")
...
par(grid)
```
I found the same error today. I have tried the "Clear all Plots" button, but it was giving me the same error. Then this trick worked for me,
Try to increase the plot area by dragging. It will help you for sure.
I have just use the Clear all plots then again give the plot command and it was helpfull

How to plot dendrograms with large datasets?

I am using ape (Analysis of Phylogenetics and Evolution) package in R that has dendrogram drawing functionality. I use following commands to read the data in Newick format, and draw a dendrogram using the plot function:
library("ape")
gcPhylo <-read.tree(file = "gc.tree")
plot(gcPhylo, show.node.label = TRUE)
As the data set is quite large, it is impossible to see any details in the lower levels of the tree. I can see just black areas but no details. I can only see few levels from the top, and then no detail.
I was wondering if there is any zoom capability of the plot function. I tried to limit the area using xLim and yLim, however, they just limit the area, and do not zoom to make the details visible. Either zooming, or making the details visible without zooming will solve my problem.
I am also appreciated to know any other package, function, or tool that will help me overcoming the problem.
Thanks.
It is possible to cut a dendrogram at a specified height and plot the elements:
First create a clustering using the built-in dataset USArrests. Then convert to a dendrogram:
hc <- hclust(dist(USArrests))
hcd <- as.dendrogram(hc)
Next, use cut.dendrogram to cut at a specified height, in this case h=75. This produces a list of a dendrogram for the upper bit of the cut, and a list of dendograms, one for each branch below the cut:
par(mfrow=c(3,1))
plot(hcd, main="Main")
plot(cut(hcd, h=75)$upper,
main="Upper tree of cut at h=75")
plot(cut(hcd, h=75)$lower[[2]],
main="Second branch of lower tree with cut at h=75")
The cut function described in the other answer is a very good solution; if you would like to maintain the whole tree on one page for some interactive investigation you could also plot to a large page on a PDF.
The resulting PDF is vectorized so you can zoom in closely with your favourite PDF viewer without loss of resolution.
Here's an example of how to direct plot output to PDF:
# Open a PDF for plotting; units are inches by default
pdf("/path/to/a/pdf/file.pdf", width=40, height=15)
# Do some plotting
plot(gcPhylo)
# Close the PDF file's associated graphics device (necessary to finalize the output)
dev.off()

Resources