ggsurvplot changing confidence interval line size - r

Trying to change the line size of my confidence interval using ggsurvplot. When I use change the size to 1 or 2, it only affects the size of the center line, and not the size of the confidence interval lines. Any suggestions on how to alter the size of those lines?
Here is my code:
ggsurvplot(ovlsfit,
surv.scale="percent",
title="Survival Curve",
xlim=c(-0.02,5.1),
xlab=c("Time (y)"),
break.x.by=1,
censor=FALSE,
axes.offset=FALSE,
conf.int.style=c("step"),
legend=c("none"),
linetype = "strata",
color="black",
size=0.8,
risk.table=TRUE,
risk.table.height=0.18,
risk.table.pos=c("out"),
risk.table.fontsize=4)
And output:

Let's create a model similar to yours for demonstration:
library(survival)
library(survminer)
ovlsfit <- survfit(Surv(time/660, status) ~ 1, data = colon)
Now we will try to recreate your plot:
p <- ggsurvplot(ovlsfit,
surv.scale = "percent",
title = "Survival Curve",
xlim = c(-0.02,5.1),
xlab = c("Time (y)"),
break.x.by = 1,
censor = FALSE,
axes.offset = FALSE,
conf.int.style = c("step"),
legend = c("none"),
linetype = 'strata',
palette = "black",
size = 0.8,
risk.table = TRUE,
risk.table.height = 0.18,
risk.table.pos = c("out"),
risk.table.fontsize = 4)
p
Unfortunately, there is no direct access to the confidence interval line size from within the call to ggsurvplot, but we can easily access the layers they are in and change the line size directly. Here, we will make them large for demonstration purposes:
p$plot$layers[[3]]$aes_params$size <- 2
p$plot$layers[[4]]$aes_params$size <- 2
p

Related

Labeling contour lines in R using metR with gratia or ggplot2

Some ways to add labels on contour plots
# load packages
library('mgcv')
library('gratia') # draw(); smooth_estimates()
library('metR') # geom_contour2(); geom_text_contour()
library('ggplot2')
Simulate data using the example from Gavin Simpson's website: https://fromthebottomoftheheap.net/2018/10/23/introducing-gratia/
set.seed(1)
dat <- gamSim(2, n = 4000, dist = "normal", scale = 1, verbose = FALSE)
mod <- gam(y ~ s(x, z, k = 30), data = dat$data, method = "REML")
sm <- smooth_estimates(mod); sm
Plot using gratia with the number of contour lines automatically adjusted:
draw(mod) +
geom_text_contour(
aes(z = est), # 'est' from smooth_estimates(mod)
colour = "black", size = 4.5, fontface = "bold",
stroke = 0.3, stroke.colour = "white", # 'stroke' controls the width of stroke relative to the size of the text
skip = 0, # number of contours to skip
rotate = FALSE, # horizontal labeling; if TRUE, rotate text following the contour
label.placer = label_placer_fraction(frac = 0.5)) # 'frac = 0.5' places the label at equal distance from extremities. Try 'label.placer = label_placer_n(2)' to display two labels per contour line
However, contour lines and labeling do no longer match if we use e.g. 'n_contour = 10' within draw().
To allow this matching, use 'n_contour = 0' within draw(), define 'binwidth' within geom_contour2() and 'breaks' within geom_text_contour(), as follows.
Plot using gratia::draw with 'binwidth'-adjusted contour lines:
min(sm$est); max(sm$est) # find min() and max() for adjusting the 'est' z-scale
draw(mod, n_contour = 0) +
geom_contour2(aes(z = est), binwidth = 0.2) +
geom_text_contour(
aes(z = est), # 'est' from smooth_estimates(mod)
breaks = seq(-0.4, 0.4, by = 0.2), # 'breaks' must match with 'binwidth' above
colour = "black", size = 4.5, fontface = "bold",
stroke = 0.3, stroke.colour = "white", # 'stroke' controls the width of stroke relative to the size of the text
skip = 0, # number of contours to skip
rotate = FALSE, # horizontal labelling; if TRUE, rotate text following the contour
label.placer = label_placer_fraction(frac = 0.5)) # 'frac = 0.5' places the label at equal distance from contour lines' extremities. Try 'label.placer = label_placer_n(2)' to display two labels per contour line
Also possible to customize the graph directly with ggplot2:
ggplot(data = sm, aes(x = x, y = z, z = est)) +
geom_contour2(aes(z = est), binwidth = 0.1) +
geom_text_contour(
aes(z = est), # 'est' from smooth_estimates(mod)
breaks = seq(-0.4, 0.4, by = 0.1), # 'breaks' instead of 'bins' to not have too many decimals
colour = "black", size = 4.5, fontface = "bold",
stroke = 0.3, stroke.colour = "white", # 'stroke' controls the width of stroke relative to the size of the text
skip = 0, # number of contours to skip
rotate = FALSE, # horizontal labelling; if TRUE, rotate text following the contour
label.placer = label_placer_fraction(frac = 0.5)) # 'frac = 0.5' places the label at equal distance from contour lines' extremities. Try 'label.placer = label_placer_n(2)' to display two labels per contour line
You can use geom_textcontour from geomtextpath to obtain nicely placed labels without having to tweak lots of different parameters:
library(geomtextpath)
ggplot(sm, aes(x, z, z = est)) + geom_textcontour()
To use it within the gratia::draw framework, you can remove the existing contour from the plot first:
p <- draw(mod)
p$layers[[2]] <- NULL
p + geom_textcontour(aes(z = est), fontface = 'bold')
EDIT
To get a similar effect to the stroke parameter we can do:
library(ggfx)
p + with_outer_glow(geom_textcontour(aes(z = est), fontface = 'bold',
linetype = NA),
colour = 'white', expand = 3, sigma = 1) +
geom_textcontour(aes(z = est), fontface = 'bold', textcolour = NA)

How to add CI error bars and edit an interception plot in plot_model for a glmer?

I am studying how long it takes for individuals diagnosed with a psychiatric condition, compared to healthy individuals, to detect fearful, happy and neutral emotional faces.
I am performining analysis with Generalized Linear Mixed Model, and the best-fitting model was the following:
gmod3.5 <- glmer(rt ~ Group * Emotion + trialnum2 +(1+Emotion|ID)+(1|Actor), data=CFS_21, family=Gamma(link="identity"))
The factor group has two levels (SZ, CG), the factor emotion has tree leves (F, H, N) and age is centered.
For the plot, I wrote the following code:
set_theme(base = theme_classic(), #To remove the background color and the grids
axis.title.size = 1.0, #To change axis title size
axis.textsize.x = 1.0, #To change x axis text size
axis.textsize.y = 1.0,
legend.item.backcol = "white",
legend.item.bordercol = "white",
legend.backgroundcol = "white",
legend.inside = TRUE)
p<-plot_model(gmod3.5, type = "int", vars = c("Emotion", "Group", "trialnum2"),
title="Response time per group considering the emotion",
colors = "Set2",
show.values = TRUE,
value.offset = .2,
value.size = 2,
dot.size = 2,
line.size = 1,
width = 1)
p + scale_y_continuous(limits = c(0, 4), breaks = c(0, 1, 2, 3, 4))
However, I need to use CI for the error bars and to make the groups (CG and SZ) closer to each other
Does anyone known how to do this using the plot_model function?

Add calculated mean value to vertical line in plot in R

I have created a density plot with a vertical line reflecting the mean - I would like to include the calculated mean number in the graph but don't know how
(for example the mean 1.2 should appear in the graph).
beta_budget[,2] is the column which includes the different numbers of the price.
windows()
plot(density(beta_budget[,2]), xlim= c(-0.1,15), type ="l", xlab = "Beta Coefficients", main = "Preis", col = "black")
abline(v=mean(beta_budget[,2]), col="blue")
legend("topright", legend = c("Price", "Mean"), col = c("black", "blue"), lty=1, cex=0.8)
I tried it with the text command but it didn't work...
Thank you for your advise!
Something along these lines:
Data:
set.seed(123)
df <- data.frame(
v1 = rnorm(1000)
)
Draw histogram with density line:
hist(df$v1, freq = F, main = "")
lines(density(df$v1, kernel = "cosine", bw = 0.5))
abline(v = mean(df$v1), col = "blue", lty = 3, lwd = 2)
Include the mean as a text element:
text(mean(df$v1), # position of text on x-axis
max(density(df$v1)[[2]]), # position of text on y-axis
mean(df$v1), # text to be plotted
pos = 4, srt = 270, cex = 0.8, col = "blue") # some graphical parameters

contourplot color and labels options in Lattice for R

I am quite new to Lattice and I am stuck with some possibly basic coding. I am using shapefiles and geoTIFFS to produce maps of animals distribution and in particular I have:
1 x point shapefile
2 x geoTIFF
1 x polygon shapefile
I am overlapping a levelplot of one of the geoTIFF (UD generated with adehabitatHR) with a contourplot of the same geoTIFF at specific intervals (percentile values), a contourplot of the second geoTIFF (depth raster from ETOPO2) for three specific values (-200, -1000 and -2000), the point shapefile (animal locations) and the polygon shapefile (land). All works fine but I need to change the font size of contour plot labels, their length (i.e. from 0.12315 to 0.123) and positioning for all the contourplots. For the depth contourplot I would like to change the style of each line in something like "continous line", "dashed line" and "point line", and for the contourplot of the UD I would like to change the color of each line using a yellow to red palette.
As far as I understand, I should use panel functions to implement these changes (e.g. Controlling z labels in contourplot) but i am not quite sure how to do it. Part of my code to generate the "plot":
aa <-
quantile(
UD_raster,
probs = c(0.25, 0.75),
type = 8,
names = TRUE
)
my.at <- c(aa[1], aa[2])
depth<-c(-100, -200, -2000)
levelplot(
UD_raster,
xlab = "",
ylab = "",
margin = FALSE,
contour = FALSE,
col.regions = viridis(100),
main = "A",
maxpixels = 2e5
) + layer(sp.polygons(Land, fill = "grey40", col = NA)) + layer(sp.points(locations, pts = 2, col = "red")) + contourplot(
UD_raster,
at = my.at,
labels = TRUE,
margin = FALSE
) + contourplot(
ETOPO2,
at = depth,
labels = TRUE,
margin = FALSE
)
A simplified image, with no UD layer and no point shapefile can be found here and as you can see it is pretty messy. Thanks for your help.
So far for the ETOPO2 countourplot I have solved by eliminating the labels and adding the argument lty to style the line. Because I can't figure out how to use lty with different values for each single line in my contour, I have replicated the contourplot function three times on the same surface, one for each contour I am interested into (this was easy because I only need three contours).
For the position, font and font size of the labels of the remaining contourplot I have used
labels = list(cex = 0.8, "verdana"),
label.style = "flat"
To "shorten" the length of the labels I have used the function round where I specify to which decimal digit to round number.
So now my new code looks like:
aa <-
quantile(
UD_raster,
probs = c(0.25, 0.75),
type = 8,
names = TRUE
)
my.at <- c(aa[1], aa[2])
my.at <- round(my.at, 3)
levelplot(
UD_raster,
xlab = "",
ylab = "",
margin = FALSE,
contour = FALSE,
col.regions = viridis(100),
main = "A",
maxpixels = 2e5
) + layer(sp.polygons(Land, fill = "grey40", col = NA)) + layer(sp.points(positions, pts = 2, col = "red")) + contourplot(
UD_raster,
at = my.at,
labels = list(cex = 0.8, "verdana"),
label.style = "flat",
margin = FALSE
) + contourplot(
ETOPO2,
at = -200,
labels = FALSE,
margin = FALSE,
lty = 1,
pretty = TRUE
) + contourplot(
ETOPO2,
at = -1000,
labels = FALSE,
margin = FALSE,
lty = 2,
pretty = TRUE
) + contourplot(
ETOPO2,
at = -2000,
labels = FALSE,
margin = FALSE,
lty = 3,
pretty = TRUE
)
As one could expect, it takes a bit longer to produce the plot. Still no idea on how to change the colors of the UD contourplot.

Is there a way to use R to break chart axis and break linear regression line?

I'm trying to figure out how to modify a scatter-plot that contains two groups of data along a continuum separated by a large gap. The graph needs a break on the x-axis as well as on the regression line.
This R code using the ggplot2 library accurately presents the data, but is unsightly due to the vast amount of empty space on the graph. Pearson's correlation is -0.1380438.
library(ggplot2)
p <- ggplot(, aes(x = dis, y = result[, 1])) + geom_point(shape = 1) +
xlab("X-axis") +
ylab("Y-axis") + geom_smooth(color = "red", method = "lm", se = F) + theme_classic()
p + theme(plot.title = element_text(hjust = 0.5, size = 14))
This R code uses gap.plot to produce the breaks needed, but the regression line doesn't contain a break and doesn't reflect the slope properly. As you can see, the slope of the regression line isn't as sharp as the graph above and there needs to be a visible distinction in the slope of the line between those disparate groups.
library(plotrix)
gap.plot(
x = dis,
y = result[, 1],
gap = c(700, 4700),
gap.axis = "x",
xlab = "X-Axis",
ylab = "Y-Axis",
xtics = seq(0, 5575, by = 200)
)
abline(v = seq(700, 733) , col = "white")
abline(lm(result[, 1] ~ dis), col = "red", lwd = 2)
axis.break(1, 716, style = "slash")
Using MS Paint, I created an approximation of what the graph should look like. Notice the break marks on the top as well as the discontinuity between on the regression line between the two groups.
One solution is to plot the regression line in two pieces, using ablineclip to limit what's plotted each time. (Similar to #tung's suggestion, although it's clear that you want the appearance of a single graph rather than the appearance of facets.) Here's how that would work:
library(plotrix)
# Simulate some data that looks roughly like the original graph.
dis = c(rnorm(100, 300, 50), rnorm(100, 5000, 100))
result = c(rnorm(100, 0.6, 0.1), rnorm(100, 0.5, 0.1))
# Store the location of the gap so we can refer to it later.
x.axis.gap = c(700, 4700)
# gap.plot() works internally by shifting the location of the points to be
# plotted based on the gap size/location, and then adjusting the axis labels
# accordingly. We'll re-compute the second half of the regression line in the
# same way; these are the new values for the x-axis.
dis.alt = dis - x.axis.gap[1]
# Plot (same as before).
gap.plot(
x = dis,
y = result,
gap = x.axis.gap,
gap.axis = "x",
xlab = "X-Axis",
ylab = "Y-Axis",
xtics = seq(0, 5575, by = 200)
)
abline(v = seq(700, 733), col = "white")
axis.break(1, 716, style = "slash")
# Add regression line in two pieces: from 0 to the start of the gap, and from
# the end of the gap to infinity.
ablineclip(lm(result ~ dis), col = "red", lwd = 2, x2 = x.axis.gap[1])
ablineclip(lm(result ~ dis.alt), col = "red", lwd = 2, x1 = x.axis.gap[1] + 33)

Resources