How to adjust column width in dataframe of foretsplotter function - r

I am trying to create a forestplot, using forestplotter function, am able to get a beautiful graph, but am not able to see the entire graph, the column widths in few of the columns are so big, even if the string size is less, making the width of the entire graph, so big to see, can someone help me with this and also is it possible to align the datahrame contents uniformly centre aligned......Please help me with this
The code and relevant data are
###Required packages###
library(grid)
library(forestploter)
library(rmeta)
library(gridExtra)
#Data entered#
df <- data.frame(Study=c("A","B","C","D","Summary"),
nA = c(24,187,36,26,273),
median_A = c(4.9,5.69,8.866995074,8.5,NA),
Q1A =c(3,2.86,4.495073892,2,NA),
Q3A =c(8.5,9.78,14.96305419,32,NA),
nP = c(23,193,36,26,278),
median_P = c(7.2,6.79,8.990147783,12.5,NA),
Q1P =c(3.4,3.59,4.002463054,2,NA),
Q3P =c(10.9,10.12,12.06896552,43,NA),
W = c("10.6%","80.8%","8.0%","0.70%",NA),
E=c(-2.3,-1.1,-0.123152709,-4,-1.16881587),
UL=c(1.161473203,0.156288294,3.881699516,10.02689306,-0.039791047),
LL=c(-5.761473203,-2.356288294,-4.128004935,-18.02689306,-2.297840692))
#Calculate SE for box size#
df$SE <- (df$UL-df$E)/1.96
#Column for Confidence intervals for Drug A and Placebo, with 2 significant digit#
df$IQRA <- sprintf("%.2f (%.2f to %.2f)",df$median_A,df$Q1A, df$Q3A)
df$IQRP <- sprintf("%.2f (%.2f to %.2f)",df$median_P,df$Q1P, df$Q3P)
#Column for Confidence intervals for NET EFFECT, with 2 significant digit#
df$MD <- sprintf("%.2f (%.2f to %.2f)", df$E, df$LL, df$UL)
#Create a column with space for forest plot#
df$" "<- paste(rep(" ", 16), collapse = " ")
##Forest plot theme##
#To be modified as needed#
ftn <-forest_theme(
base_size = 16,
base_family = "serif",
ci_pch = 15,
ci_col = "black",
ci_lty = 1,
ci_lwd = 1,
ci_Theight = 0.25,
legend_name = " ",
legend_position = "right",legend_value = "",
xaxis_lwd = 1,
xaxis_cex = 0.7,
refline_lwd = 1,
refline_lty = "dashed",
refline_col = "red",
summary_fill = "blue",
summary_col = "blue",
footnote_cex = 0.4,
footnote_fontface = "plain",
footnote_col = "black",
title_just = c("center"),
title_cex = 1.1,
title_fontface = "bold",
title_col = "black",
show.rownames = FALSE)
##Table in Order for Forest plot##
#First get Column names#
colnames(df)
df2 <-df[,c(1,2,15,6,16,18,17)]
#Make NA cells empty
df2[5,3] <-c(" ")
df2[5,5] <-c(" ")
##Forestplot##
plot<-forest(df2,
est = df$E,
lower = df$LL,
upper = df$UL,
sizes = (df$SE/10),
ci_column = 6,
ref_line = 0,
arrow_lab = c("Drug A Better", "Placebo Better"),
xlim = c(-7, 6),
is_summary = c(FALSE,FALSE,FALSE,FALSE,TRUE),
xlog = FALSE,
ticks_digits = 0,ticks_at = c(-6,0,6),
theme = ftn)
##Show plot
print(plot, autofit = FALSE)

Related

Why do RadarCharts graph incorrectly in R? (fmsb)

create_beautiful_radarchart <- function(data, color = "#800000",
vlabels = colnames(data), vlcex = 0.7,
caxislabels = NULL, title = NULL, ...){
radarchart(
data, axistype = 1,
pcol = color, pfcol = scales::alpha(color, 0.5), plwd = 2, plty = 1,
cglcol = "grey", cglty = 1, cglwd = 0.8,
axislabcol = "grey",
vlcex = vlcex, vlabels = vlabels,
caxislabels = caxislabels, title = title, ...
)
}
colors <- c("#00AFBB", "#E0115F", "#800000", "orange")
titles <- c("UnderWeight", "NormalWeight", "OverWeight", "Obese")
for(i in 1:4){
create_beautiful_radarchart(
data = df[c(1,2,3,4),], caxislabels = c(5000,10000,15000,20000),
color = colors[i], title = titles[i],
seg=3)
}
Why does my code produce radarcharts like:
Here is my entire dataset:
NORTHEAST
NORTHWEST
SOUTHEAST
SOUTHWEST
UNDERWEIGHT
8914.424
9223.351
0.00
7778.771
NORMALWEIGHT
11151.782
10032.507
13286.81
7246.518
OVERWEIGHT
10818.594
11503.929
10846.20
10786.970
OBESE
16606.763
14198.111
16139.57
14752.032
The first two rows of your data frame have to be the maximum and minimum values you want plotted for that series. Since you are filling the areas, you will need to make the colors for the macimum and minimum values NA. You can automate the ranges for each series like this:
range <- as.data.frame(lapply(df, function(x) rev(range(pretty(x)))))
And presumably you want 4 separate radar plots, in which case you can do:
for(i in 1:4){
create_beautiful_radarchart(
data = rbind(range, df[i,]), caxislabels = c(5000,10000,15000,20000),
color = c(NA, NA, colors[i]), title = titles[i],
seg=3)
}

empty output for wgcna scatterplot in R

I am trying to run this code for wgcna to relate modules * traits:
weight <- as.data.frame(datTraits[, "weight", drop = FALSE])
names(weight) = "weight"
modNames = substring(names(MEs), 3)
geneModuleMembership = as.data.frame(cor(datExpr, MEs, use = "p"));
MMPvalue = as.data.frame(corPvalueStudent(as.matrix(geneModuleMembership), nSamples));
names(geneModuleMembership) = paste("MM", modNames, sep="");
names(MMPvalue) = paste("p.MM", modNames, sep="");
geneTraitSignificance = as.data.frame(cor(datExpr, weight, use = "p"));
GSPvalue = as.data.frame(corPvalueStudent(as.matrix(geneTraitSignificance), nSamples));
names(geneTraitSignificance) = paste("GS.", names(weight), sep="");
names(GSPvalue) = paste("p.GS.", names(weight), sep="");
##Plotting the graph
module = "plum1"
column = match(module, modNames);
moduleGenes = moduleColors==module;
pdf("plum1.pdf", width = 7, height = 7);
par(mfrow = c(1,1));
verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
abs(geneTraitSignificance[moduleGenes, 1]),
xlab = paste("Module Membership in", module, "module"),
ylab = "Gene significance",
main = paste("Module membership vs. gene significance\n"),
cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
It runs without any error but does not give the scatter plot output. Thank you!

For-loop to dynamically change plot title

I have 5 variables which want to plot and export in one pdf. However, I have some trouble wiht the for-loop I am running,
parC <-list(unit = 100,labelx = "Time",labely = "Time",cols = "black",
pcex = .01, pch = 1,las = 1,
labax = seq(0,nrow(RP),100),
labay = seq(0,nrow(RP),100))
pdf("filename.pdf", onefile=TRUE)
for (i in RP_values){ # the values that are plotted
for (j in name) { # name is a list of names, so that the title changes dynamically
plotting(i, parC, j)
}
}
dev.off()
RP_values = list of values that is plotted
name = list of names to dynamically change the plotting title
plotting = an adjusted version from the plotRP() function of the crqa package. Here I added a main title to the plot.
The code for the plotting() function:
plotting <- function(RP, par, x){
if (exists("par") == FALSE){ # we use some defaults
## default values
unit = 2; labelx = "Time"; labely = "Time"
cols = "black"; pcex = .3; pch = 1; las = 0;
labax = seq(0, nrow(RP), unit); labay = seq(0, nrow(RP), unit);
} else { # we load the values that we desire
for (v in 1:length(par)) assign(names(par)[v], par[[v]])
}
xdim = nrow(RP)
ydim = ncol(RP)
RP = matrix(as.numeric(RP), nrow = xdim, ncol = ydim) # transform it for plotting
ind = which(RP == 1, arr.ind = T)
tstamp = seq(0, xdim, unit)
par(mar = c(5,5, 1, 3), font.axis = 2, cex.axis = 1,
font.lab = 2, cex.lab = 1.2)
plot(tstamp, tstamp, type = "n", xlab = "", ylab = "", xaxt = "n", yaxt = "n", main = x)
matpoints(ind[,1], ind[,2], cex = pcex, col = cols, pch = pch)
mtext(labelx, at = mean(tstamp), side = 1, line = 2.2, cex = 1.2, font = 2)
mtext(labely, at = mean(tstamp), side = 2, line = 2.2, cex = 1.2, font = 2)
# if (is.numeric(labax)){ ## it means there is some default
# mtext(labax, at = seq(1, nrow(RP), nrow(RP)/10), side = 1, line = .5, cex = 1, font = 2)
# mtext(labay, at = seq(1, nrow(RP), nrow(RP)/10), side = 2, line = .5, cex = 1, font = 2)
# } else{
mtext(labax, at = tstamp, side = 1, line = .5, cex = .8, font = 2, las = las)
mtext(labay, at = tstamp, side = 2, line = .5, cex = .8, font = 2, las = las)
# }
}
My problem is instead of 5 plots I get 25, where each plot appears 5 times, but with a different title. If I do not include the "j" part everything works fine, but of course do not have any main title for each plot.
I appreciate any help.
Best,
Johnson
From your description and comments, it appears you need an elementwise loop and not a nested loop. Consider retrieving all pairwise combinations of names and RP_values with expand.grid and iterate through them with mapply. Also, since parC depends on nrows of corresponding RP, have parC defined inside function for only two parameters (with more informative names like title instead of x):
plotting <- function(RP, title) {
parC <- list(unit=100, labelx="Time", labely="Time",
cols="black", pcex=.01, pch=1, las=1,
labax=seq(0, nrow(RP), 100),
labay=seq(0, nrow(RP), 100))
...
plot(tstamp, tstamp, type="n", xlab="", ylab="",
xaxt="n", yaxt="n", main=title)
...
}
params <- expand.grid(RP_values=RP_values, name=name)
out <- mapply(plotting, RP=params$RP_values, title=params$name)

Radar chart is not displaying the values accurately on the axis

I am trying to create a radar chart but the axis stops at 4 when the maximum I have given is 10. Any help is much appreciated.
I have taken a subset of the dataset from a .csv file. Below is the subset
datasample = structure(list(Score = 7.522, Whisker.high = 7.581728, Whisker.low = 7.462272,
GDP = 1.482383, Family = 1.551122, Health = 0.7925655, Freedom = 0.6260067,
Generosity = 0.3552805, TrustInGovernmentAndCorruption. = 0.4007701,
Dystopia.Residual = 2.3137), .Names = c("Score", "Whisker.high",
"Whisker.low", "GDP", "Family", "Health", "Freedom", "Generosity",
"TrustInGovernmentAndCorruption.",
"Dystopia.Residual"), class = "data.frame", row.names = c(NA,
-1L))
The subset contains 10 columns and 1 row.
Code:
library(fmsb)
#data <- read.csv("~/Desktop/App-1/2017.csv")
#datasample <- data[2, 3:12]
datasample <- rbind(rep(10,12), rep(0,12), datasample)
radarchart(datasample, axistype = 1,
pcol = rgb(0.2,0.5,0.5,0.9), pfcol = rgb(0.2,0.5,0.5, 0.5), plwd = 4,
cglcol = "grey", cglty = 1, axislabcol = "grey",caxislabels = seq(0,20,1), cglwd = 0.8,
vlcex = 0.8)
Here is the chart created:
The highest value in the subset (datasample) is 7.581728 but the chart does not display that value. How do I fix this?
The radar plot you are generating has an axis that is percentages of the max data point (you can see these when you remove the caxislabels from your plot (you'll get 100%,75%,50%,25%). The values you are seeing around 3 are actually the ~7.5 values (on the 75% grid line).
One way to fix this so that the axis is as expected:
radarchart(datasample, axistype = 1,
pcol = rgb(0.2,0.5,0.5,0.9), pfcol = rgb(0.2,0.5,0.5, 0.5), plwd = 4,
cglcol = "grey", cglty = 1, axislabcol = "grey",
caxislabels = seq(min(datasample),max(datasample),1), seg=length(seq(min(datasample),max(datasample),1))-1,
cglwd = 0.8, vlcex = 0.8)

How to return a value if an error-free R function does not do so

My goal is to assign a plot produced by the pyramid package to a list. Later, I will have that plot and others inserted from the list into a document. But the pyramid function appears not to return a value. How can I assign the pyramid plot to an object?
install.packages("pyramid") # functions to draw a population pyramid
library(pyramid)
# create a mock data frame to comparing this plot to a counterpart from plotrix
df <- data.frame(level1 = c(9,9,4,3,34,28), levelsame = c(9,9,4,3,34,28),
title = c("Dir", "Exec. Dir", "Mgr", "Sr. Mgr", "Mgt Princ", "EVP+"))
# assign the plot (hopefully) to an object
empty <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> empty
NULL
Likewise, if I assign the pyramid call to my list, nothing happens. There is no value for the list returned by pyramid.
plotlist2[["pyramid"]] <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> plotlist2[1]
[[1]]
NULL
I fear I am blundering in some obvious mis-understanding, so I welcome being set aright. Thank you.
You can use the recordPlot() function to save the current plot to a variable.
In your case you could do:
#print the plot
pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
#save the current printed plot
pyrPlot<-recordPlot()
#plot it again
pyrPlot
You might have to enable the displaylist using dev.control(displaylist ="enable") for this to work depending on the graphical device you are using

Resources