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)
}
Related
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)
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)
I am using twoord.plot for the first time, and I am having trouble getting the x axis set to years for a time-series data set. I have two different y-axes on different scales. Here is the code that I am working with.
#Install BatchGetSymbols
install.packages('BatchGetSymbols')
library(BatchGetSymbols)
#Get data from FRED
library(quantmod)
getSymbols('CPALTT01USM661S', src = 'FRED')
library(quantmod)
getSymbols('M2SL', src = 'FRED')
#Create data sets with equal number of observations
CPI = CPALTT01USM661S["1960-01-01/2019-01-01"]
M2 = M2SL["1960-01-01/2019-01-01"]
library(plotrix)
twoord.plot(rx = time(CPI), ry = CPI, lx = time(CPI), ly = M2,
main = "Money Supply and Prices",
xlim = NULL, lylim = NULL, rylim = NULL,
mar = c(5,4,4,4), lcol = "red", rcol = "blue", xlab = "", lytickpos = NA,
ylab = "M2", ylab.at = NA,
rytickpos = NA, rylab = "CPI", rylab.at = NA, lpch = 1,rpch = 2,
type = "l", xtickpos = NULL, xticklab = NULL,
halfwidth = 0.4, axislab.cex = 1, do.first = NULL)
Here is the graph that I am getting. Notice the x-axis is not in years.
The date values ( beginnings of each month) are in the index of the matrices, so to extract the year beginnings get every 12th item:
twoord.plot(rx=time(CPI), ry=CPI, lx=time(CPI),ly = M2, main="Money Supply and Prices",xlim=NULL,lylim=NULL,rylim=NULL,
mar=c(5,4,4,4),lcol="red",rcol="blue",xlab="",lytickpos=NA,ylab="M2",ylab.at=NA,
rytickpos=NA,rylab="CPI",rylab.at=NA,lpch=1,rpch=2,
type="l",
xtickpos=index(CPI)[seq(1,nrow(CPI), by=12)], #tick at year start
xticklab=format( index(CPI)[seq(1,nrow(CPI), by=12)], "%Y"), #just year
halfwidth=0.4, axislab.cex=1,
do.first=NULL, las=2) # not sure why las=2 didn't seem to work.
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)
The code I found creates a population matrix node diagram. All I want to do is add a self arrow on the final node i.e. one that points to itself. Hope you can help.
library(diagram)
Numgenerations <- 6
DiffMat <- matrix(data = 0, nrow = Numgenerations, ncol = Numgenerations)
AA <- as.data.frame(DiffMat)
AA[[1,5]] <- "f[4]"
AA[[1,6]] <- "f[5]"
#
AA[[2,1]] <- "s[list(0,1)]"
AA[[3,2]] <- "s[list(1,2)]"
AA[[4,3]] <- "s[list(2,3)]"
AA[[5,4]] <- "s[list(3,4)]"
AA[[6,5]] <- "s[list(4,5)]"
#
name <- c(expression(Age[0]), expression(Age[1]), expression(Age[2]),
expression(Age[3]), expression(Age[4]), expression(Age[5]))
#
plotmat(A = AA, pos = 6, curve = 0.7, name = name, lwd = 2,
arr.len = 0.6, arr.width = 0.25, my = -0.2,
box.size = 0.05, arr.type = "triangle", dtext = 0.95,
main = "Age-structured population model")
You can add the arrow this way:
AA[[6,6]] <- "s[list(5,5)]"
Or, if you want it labeled as a self arrow,
AA[[6,6]] <- "self"
I needed to set relsize to slightly less than 1 to prevent the self arrow from being clipped at the right edge.
plotmat(A = AA, pos = 6, curve = 0.7, name = name, lwd = 2,
arr.len = 0.6, arr.width = 0.25, my = -0.2,
box.size = 0.05, arr.type = "triangle", dtext = 0.95,
main = "Age-structured population model",
relsize=0.97)