R partykit::ctree offset labels on edges - r

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))

Related

How can I make the internal node representation smaller in the plotting function of the partykit/glmertree package in R?

I am working with the glmertree package in R, which is an extension of the partykit package. I am trying to plot a model using the glmertree plotting function, which simply extends the partykit plotting function. I would like to make the circles for the internal nodes smaller in my plot so that they do not all overlap. I have extensively researched the ip_args (inner panel args) option for a party kit plot, but all I have managed to do is change the font size or the font color or what is printed in the internal node- I cannot change the circle size. Can anyone help with this?
Default plot, made with the code
plot(glmr_reasonable)
Using the code:
ip_args=list(abbreviate=FALSE, pval=FALSE, gp=gpar(cex=0.5, col="red", pin=c(0.25, 0.25)))
plot(glmr_reasonable, ip_args=ip_args)
I was able to make the following changes:
New plot
However, I don't want red text and tiny font, I want smaller circles. Does anyone know how to help?
Thanks!
The node_inner() panel function currently determines how large the label for the longest splitting variable name is and chooses the size of the ellipse correspondingly. However, due to a bug (that I just fixed on R-Forge) the gpar settings within the ip_args had not been processed correctly.
If you have one (or a few) variable name(s) that is/are quite long like STABLE_RESIDENCE then all ellipses become larger. (It would just look awkward to make this only larger for some nodes.) To save space you can either abbreviate the text or decrease the font size:
By setting ip_args = list(abbreviate = 10), say, only those variable names that are longer than 10 would get abbreviated automatically, thus making all ellipses smaller.
By decreasing the fontsize throughout the entire plot you will also make the ellipses smaller, e.g., plot(..., gp = gpar(fontsize = 9)).
Decreasing the fontsize just locally in the inner nodes (but not the rest of the tree) will also make the ellipses smaller, e.g., ip_args = list(gp = gpar(fontsize = 9)).
The last point did not work correctly up to now but I have just committed a fix to R-Forge. (To install this you currently have to check out and install by hand because R-Forge's auto-builder currently seems to hang...)

R igraph output vertice is not shown

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.

R metafor forest-plots: xlim seems to be wrongly ignored

I am using forest.rma in the R package metafor. I want to use the xlim argument to specify the width of the plot. But this gets overridden when one of the x-values is outside that range. Here are two examples:
library(metafor)
par(mfrow=c(2,1))
rmaObject <- rma.uni(yi=c(1.3, -16), sei=c(0.8, 0.7))
forest(rmaObject, atransf=exp, xlim=c(-5,12), alim=c(-5,12))$xlim
forest(rmaObject, atransf=exp, xlim=c(-5,12))$xlim
In both cases I think the function should follow my instruction to use xlim=c(-5,12) and draw just a left arrowhead for the second bar, to show that the whole of the bar lies outside the left of the plot. But as the console output shows the first one sets xlim to c(-16,12) and the second one sets it to c(-20,12).
In other words forest forces xlim to encompass both bars completely, but I don't think it should do that if I specify xlim, and especially not if I specify alim as well. Is there an easy way for me to fix this?
The numbers in this example are real, though I have omitted most of my studies (i.e. values of yi and sei), which are mostly in the area of 0 or 1.
You can install the development version of metafor as described here:
http://www.metafor-project.org/doku.php/installation#development_version
It deals with this better. It still forces xlim to encompass the yi values, but no longer for alim. The summary polygon at the bottom still looks like crap though (I haven't built in any code to cut off the polygon shape at the alim values -- not as trivial as it may seem), but this may not be an issue once you add the rest of the studies.

Shaded graph/network plot?

I am trying to plot quite large and dense networks (dput here). All I end up with is a bunch of overlapping dots, which does not really give me a sense of the structure or density of the network:
library(sna)
plot(data, mode = "fruchtermanreingold")
However, I have seen plots which utilizes fading to visualize the degree to which points overlap, e.g.:
How can I implement this "fading" in a plot of a graph?
Here's one way:
library(sna)
library(network)
source("modifieddatafromgist.R")
plot.network(data,
vertex.col="#FF000020",
vertex.border="#FF000020",
edge.col="#FFFFFF")
First, I added a data <- to the gist so it could be sourced.
Second, you need to ensure the proper library calls so the object classes are assigned correctly and the proper plot function will be used.
Third, you should use the extra parameters for the fruchtermanreingold layout (which is the default one for plot.network) to expand the area and increase the # of iterations.
Fourth, you should do a set.seed before the plot so folks can reproduce the output example.
Fifth, I deliberately removed cruft so you can see the point overlap, but you can change the alpha for both edges & vertices (and you should change the edge width, too) to get the result you want.
There's a ton of help in ?plot.network to assist you in configuring these options.

Auto fit labels in R boxplot

We are currently using R to automatically generate various kinds of boxplots.
The problem we have is that the length of our labels varies considerably between different plots and classes in one plot.
Is there a way to automatically adjust the plot so that all the labels will fit it nicely?
Specifying a worst case mar isn't feasible because in some plots the labels are considerably shorter than in others.
Lattice is the graphics library most likely to be helpful here. I say that for two reasons: (i) lattice is based on the grid system, and by accessing grid's graphical primitives, you can get much finer control over, among other things, the location of your panel output; and (ii) there's more to work with--the R standard graphics package has 70 different parameters, while Lattice has 371--by my count anyway, (length(names(unlist(trellis.par.get())))), yet those 371 are not in a flat structure like they are in the base package, but instead are collected in a hierarchical structure (with 30 or so parameter groups at the top level).
What you want is relative positioning of your axis labels. I would recommend going down one level for this sort of task. So to do what you want, just change the relevant grob slots then just redraw the two grobs (using the R interactive prompt):
library(lattice)
library(grid)
bwplot(~runif(200, 10, 99), xlab="x-axis label", ylab="y-axis label")
# move the x-axis label to the far left
grid.edit("[.]xlab$", grep=T, x=unit(0, "npc"), just="left", redraw=T)
# move it to the far right
grid.edit("[.]xlab$", grep=T, x=unit(1, "npc"), just="right", redraw=T)
# move it to the center
grid.edit("[.]xlab$", grep=T, x=unit(0.5, "npc"), just="center", redraw=T)
# same for y-axis
grid.edit("[.]ylab$", grep=T, y=unit(0.5, "npc"), just="center", redraw=T)
"[.].xlab$", grid.edit takes a gPath object (just a path traversing a gTree, which is just a grob that contains other grobs); because i didn't know where in the gPath my object of interest resides (the x-axis/y-axis label, i used a regular expression form for the object;
"grep=T", just tells grid.edit to treat the previous parameter as a regular expression;
"x=unit(0.5, 'npc')", specifying viewport coordinates here (in this case, just the x value); 'npc' ('normalized parent coordinates', which is the default) treats the viewport origin as (0,0), and assigns it a width & height of 1 unit each. Hence, i've specified the center of the viewport along the x axis.
With the base plotting system, a quick solution could be to rotate the x-labels to be vertical, using las=2 or las=3. Of course this also only works if your labels are not extremely long, but beyond a certain label length you will run into trouble with any type of plot anyway (shortening labels would be the way to go then).
But I agree with #doug that for more fine grained control, lattice or ggplot2 should be considered.

Resources