manipulate text edge labels ctree - r

Got a ctree with four labels, but the categories are long text therefore just the first is shown.
category;presence;ratio;tested;located
palindromic_recursion;1;0;0;0
conceptual_comprehension;0;1;0;0
infoxication_syndrome;0;0;1;0
foreign_words_abuse;0;0;0;1
palindromic_recursion;1;0;0;0
conceptual_comprehension;0;1;0;0
infoxication_syndrome;0;0;1;0
foreign_words_abuse;0;0;0;1
concepts.ctree <- ctree(category ~., data)
plot(concepts.ctree)
is there any way or parameter for manipultating (rotate) text, edge label names and this way force them to be all shown in plot?
My real data is much bigger but this sample is ok to test it if you do not use zoom tool.
Regards

There wasn't an option for this up to now. But I just tweaked the development version of partykit on R-Forge to support this feature. Currently, the package is re-building but hopefully you can soon say install.packages("partykit", repos = "http://R-Forge.R-project.org") - or if you don't want to wait that long, simply check out the SVN and re-build yourself.
In the new version, you can pass the rot and just arguments to grid.text() to control rotation and justification of the x-axis labels.
Read the data:
data <- read.csv2(textConnection(
"category;presence;ratio;tested;located
palindromic_recursion;1;0;0;0
conceptual_comprehension;0;1;0;0
infoxication_syndrome;0;0;1;0
foreign_words_abuse;0;0;0;1
palindromic_recursion;1;0;0;0
conceptual_comprehension;0;1;0;0
infoxication_syndrome;0;0;1;0
foreign_words_abuse;0;0;0;1"
))
Fit the tree (using the partykit implementation of ctree()):
library("partykit")
concepts.ctree <- ctree(category ~ ., data = data)
For visualization create a viewport with sufficiently large margins on the x-axis first. Then, add the tree to the existing viewport page and set the rotation/justification arguments for the barplot.
pushViewport(plotViewport(margins = c(6, 0, 0, 0)))
plot(concepts.ctree, tp_args = list(rot = 45, just = c("right", "top")),
newpage = FALSE)

Related

Strange blue subtitle when plotting objects from the RandomFields package

Theplot method for RFspatialGridDataFrame outputs a weird blue "subtitle" when passing main or axis label arguments to the plot function.
install.packages("RandomFields")
library(RandomFields)
model <- RPbernoulli(RMexp(scale = 3), threshold = 1)
set.seed(100)
simulation <- RFsimulate(model, x = 1:138, y = 1:74)
plot(simulation, main = "This is an example title")
The following is a screeshot of the output
Strangely enough, this appears to be a feature, as running other example for the RandomFields documentation shows.
Is there any way of not outputting this blue repeated title? I have tried fiddling with other graphical arguments (such as setting legend = F) but the behavior does not change.
I have contacted the maintainers of the RandomFields package, and it appears to be a setting in RFoptions.
By setting RFoptions(grPrintlevel = 0) before the plots, this behavior can be avoided. More information can be found under ?RFoptions in section 10 regarding graphics. The relevant part regarding grPrintlevel reads
grPrintlevel: integer values 0, 1, 2; only relevant when simulations are
plotted. The higher the more text is shown in the plot.
Default: 1.

Interactive plot: Manipulate contents of a ggplot2 plot with a sliding bar

Edit: Thank you to Javier for his suggestion. I forgot to mention that I would like to incorporate this interactive plot into a report / dashboard, so something that works with a HTML document from RMarkdown would be ideal, but a dashboard solution would also be fine.
Consider the following plots; the red line represents the actual data, while the green line plots predictions generated by a model:
The predictions of two different models are displayed; one trained over the first 100 hours, and the other over the first 216 hours. Predictions are then generated for the unseen data-points, then plotted.
What I would like to do, is train n models, eg. one every 12 hours in an expanding window fashion. After having done this, I would like to present the results in an interactive fashion where the user can click/slide something to move the vertical line back and forth, thereby changing which model's predictions are displayed. The point would be to intuitively show the effect of different training lengths.
I'm new to shiny and interactive plots in R; can this be done without too much trouble?
You can with the manipulate package for quick interactive plots. Shiny requires more fine-tuning and it is more time-consuming.
Here is a reproducible example for you to test out:
This creates the slider bar:
library(manipulate)
manipulate(plot(1:x), x = slider(1, 100))
Put your code here for the creation of the interactive plot:
manipulate(
plot(cars, xlim = c(0, x.max), type = type, ann = label),
x.max = slider(10, 25, step=5, initial = 25),
type = picker("Points" = "p", "Line" = "l", "Step" = "s"),
label = checkbox(TRUE, "Draw Labels"))
Check out the CRAN manipulate package for more information:
https://cran.r-project.org/web/packages/manipulate/index.html
I was able to do this with the example at the bottom of this link.
library(shiny)
sliderInput("n", "Training length:", 100, min=24, max= 11*24)
renderPlot({
plotPredictCurve(data= df, trainLength= input$n)
})

Rotate x-axis of r partykit tree plot

I've built a decision tree using ctree in R and visualize the tree using the ctree model in the party package.
I am very happy with the results and the overall visualization. However, I cannot interpret the 'confusion' in every leaf node, since the x-axis labels either overlap or are missing!
Currently I use the following command:
plot(fitCtree, main="Title", gp = gpar(fontsize = 2))
I've searched quite a lot to find the (simple?) answer... to no avail.
Can you help me out?
Cheers,
Arend
One option that is easily available in node_barplot(), the panel function employed here, is to rotate the axis labels rather than rotating the entire plot (as suggested in https://stackoverflow.com/a/12000533/4752675 mentioned by #G5W). For example you can set rot = 45, just = c("right", "top") to obtain a rotation by 45 degrees with top-right justification of the labels.
Depending on the length of the labels, it might be necessary to increase the lower margin of the plot to allow for enough space. One can do this either with pushing a separate viewport - or via the convenience argument margins that I just added to the development version of partykit on R-Forge.
As an illustration:
install.packages("partykit", repos = "http://R-Forge.R-project.org")
library("partykit")
ct <- ctree(Species ~ ., data = iris)
plot(ct, margins = c(3, 0, 0, 0),
tp_args = list(rot = 45, just = c("right", "top")))

Mosaic plot and text values

I created structable from Titanic dataset and used mosaic function for it. Everything worked great, hovewer I also wanted to label each box from mosaic plot with quantity of titanic passangers given their Class, Survival and Sex. As it turns out, I am not able to do that. I know I need to use labeling_cells to achive that, hovewer i am not able to use it (and i wan't able to find any example) in combination with stuctable and below code.
library("vcd")
struct <- structable(~ Class + Survived + Sex, data = Titanic)
mosaic(struct, data = Titanic, shade = TRUE, direction = "v")
If I understand your question correctly, then the last example in ?labeling_cells is pretty close to what you want to do. Using your example, the labeling_cells() can be added afterwards provided that the viewport tree is not popped. The only aspect that is somewhat awkward is that the struct object has to be a regular table again for the labeling. I have to ask David, the main author, whether this could be handled automatically.
mosaic(struct, shade = TRUE, direction = "v", pop = FALSE)
labeling_cells(text = as.table(struct), margin = 0)(as.table(struct))
Fixed in upstream in vcd 1.4-4, but note that you can simply use
mosaic(struct, labeling = labeling_values)

How to plot a large ctree() to avoid overlapping nodes

When I plotted the decision tree result from ctree() from party package, the font was too big and the box was also too big. They are overlapping other nodes.
Is there a way to customize the output from plot() so that the box and the font would be smaller ?
The short answer seems to be, no, you cannot change the font size, but there are some good other options.
I know of three possible solutions. First, you can change other parameters in the plot to make it more compact. Second, you can write it to a graphic file and view that file. Third, you can use an alternative implementation of ctree() in the partykit package, which is a newer package by some of the same authors.
Default Plot Example
library(party)
airq <- subset(airquality, !is.na(Ozone))
airct <- ctree(Ozone ~ ., data = airq,
controls = ctree_control(maxsurrogate = 3))
plot(airct) #default plot, some crowding with N hidden on leafs
Simplified plot
# simpler version of plot
plot(airct, type="simple", # no terminal plots
inner_panel=node_inner(airct,
abbreviate = TRUE, # short variable names
pval = FALSE, # no p-values
id = FALSE), # no id of node
terminal_panel=node_terminal(airct,
abbreviate = TRUE,
digits = 1, # few digits on numbers
fill = c("white"), # make box white not grey
id = FALSE)
)
This is somewhat better and one might be able to improve it further. To figure out these details, I originally did class(airct) which returned "BinaryTree". Armed with this info, I started reading ?plot.BinaryTree
Write to a file
A second simple solution is to write the plot to a file and then view the file. You may need to play with the settings to find the best fit.
png("airct.png", res=80, height=800, width=1600)
plot(airct)
dev.off()
Plot with partykit package instead
Finally, you can use a newer and not-yet-finished re-implementation of the party package by some of the same authors. At this point (Dec 2012), the only function they have re-done is ctree(). This version allows you to change font size.
library(partykit)
airct <- ctree(Ozone ~ ., data = airq)
class(airct) # different class from before
# "constparty" "party"
plot(airct, gp = gpar(fontsize = 6), # font size changed to 6
inner_panel=node_inner,
ip_args=list(
abbreviate = TRUE,
id = FALSE)
)
Here I have left the leafs in their default setting because I have frankly never figured out how to get it to work the way I want. I suspect this has to do with the fact that the package is incomplete (as of Dec 2012). You can read about the plot method starting with ?plot.party
Another option (that doesn't change what you want but does potentially solve the underlying problem) is to change the size of the figure itself, as I learned in my class for my assignment.
Replace the r in the below:
{r}
with:
{r, fig.width=X, fig.height=Y}
where the X and Y need to be replaced by numbers chosen by you depending on what size you think works better.
This website, talks about doing this in more detail and universally throughout the document.

Resources