Legend not showing. Error in strwidth(legend, units = "user", cex = cex, font = text.font) : plot.new has not been called yet - legend

I have the code below that is a combination of two boxplots and dot plots in one. It is a representation of barring density in 4 different species. The grey depicts the males and the tan the females.
data<-read.csv("C:/Users/Jeremy/Documents/A_Trogon rufus/Black-and-White/BARDATA_boxplots_M.csv")
datF<-read.csv("C:/Users/Jeremy/Documents/A_Trogon rufus/FEMALES_BW&Morphom.csv")
cleandataM<-subset(data, data$Age=="Adult" & data$White!="NA", select=(OTU:Density))
cleandatF<-subset(datF, datF$Age=="Adult", select=(OTU:Density))
dataM<- as.data.frame(cleandataM)
dataF<- as.data.frame(cleandatF)
library(ggplot2)
ggplot(dataM, aes(factor(OTU), Density))+
geom_boxplot(data=dataF,aes(factor(OTU),Density), fill="AntiqueWhite")+
geom_boxplot(fill="lightgrey", alpha=0.5)+
geom_point(data=dataF,position = position_jitter(width = 0.1), colour="tan")+
geom_point(data=dataM, position = position_jitter(width = 0.1), color="DimGrey")+ scale_x_discrete(name="",limits=order)+
scale_y_continuous(name="Bar Density (bars/cm)")+
theme(panel.background = element_blank(),panel.grid.minor=element_blank(),
panel.grid.major=element_blank(),axis.line = element_line(colour = "black"),
axis.title.y = element_text(colour="black", size=14),
axis.text.y = element_text(colour="black", size=12),
axis.text.x = element_text(colour="black", size=14))
This works just fine.
However, when I try to add a legend as:
legend("topright", inset=.01, bty="n", cex=.75, title="Sex",
c("Male", "Female"), fill=c("lightgrey", "black")
It returns the following Error:
Error in strwidth(legend, units = "user", cex = cex, font = text.font) :
plot.new has not been called yet
Please, is there someone who could suggest how to correct this?

Related

Non-linear regression line and its Computation failed in `stat_smooth()`: argument "p" is missing, with no default error

I have been trying to fit a non-linear regression line into my standard curve. However, I am getting the following error:
The main problem is that with the linear regression line I could use a simple command like:
stat_cor(label.y = c(825),
label.x = c(0.88),
aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")))+
stat_regline_equation(label.x=0.88, label.y=750)+
And the equation for the linear regression line with an a, and b values appear. In this case after using the following:
stat_smooth(method= "nlm",
formula = y~a*x/(b+x),
method.args = list( start = c(a = 3.8, b = 1457.2)),
se=FALSE)+
I am getting the above error.
You may ask where I got the a, and b values? I got them from:
nls(y~a*x/(b+x))
That has shown:
I do not know where I am making mistakes.
This is the entire code for my graph
library(tidyverse)
library(tidyr)
library(dplyr)
library(readr)
library(ggplot2)
library(ggpubr)
ggplot(data = STD, aes(x = Absorbance, y = STD)) +
labs(title = "Quantifying PGD2 in cell culture lysates and its enzymatic reactions ",
caption = "PGD2 ELISA")+
geom_point(colour = "#69b3a2")+
stat_smooth(method= "nlm",
formula = y~a*x/(b+x),
method.args = list( start = c(a = 3.8, b = 1457.2)),
se=FALSE)+
xlab(expression(paste("%B/"~B[0])))+
ylab(expression(paste("Prostaglandin"~ D[2], ~~ " MOX Concentration (pg/ml) ")))+
theme(plot.background = element_rect(fill = "transparent"),
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"))+
theme(legend.spacing.y = unit(0.01, "cm"))+
theme(legend.position = c(0.77, .91),
legend.background = element_rect(colour = NA, fill = NA))+
theme(plot.title = element_text(size = 12, face = "bold.italic"),
plot.caption = element_text(hjust = 0))
That gives the following outcome
And this is DataUsed
So, I think I have found a solution to my problem. I installed the install.packages(drc) in which the four parametric function is included. I set up my data model <- drm(STD ~ Absorbance, fct = LL.4(), data = STD), then plot(model) , and I got
I know it requires some alternations to make it look more professional, but it is just a cosmetic thing that I should be fine to do. Thank you #stefan for your time.

Center the plot title in ggsurvplot

I'm struggling with getting my plot title to the center using ggsurvplot...
I've seen some posts mentioning something like xxxx$plot + theme(....)
but this solution does not seem to work for me.
Here's my code, maybe you can see what I'm missing:
surv_object_CA19.9 <- Surv(time = data_OS$OS_Days / 30, event = data_OS$Status.Death)
CA19.9_surv_fit <- survfit(surv_object_CA19.9 ~ CA19.9.initial_status, data = data_OS)
CA19.9_OS <- ggsurvplot(CA19.9_surv_fit, data = data_OS, pval = TRUE, xlab = "Time [Months]",
ylab = "Overall survival", risk.table = TRUE, legend.title = "",
risk.table.col. = "strata", risk.table.y.text = FALSE, surv.scale = "percent",
break.x.by = 6, xlim = c(0, 60), legend.labs = c("Pathological", "Normal"),
title = "Overall survival for patients with initially pathological or normal CA19-9 values",
CA19.9_OS$plot + theme(plot.title = element_text(hjust = 0.5)))
Thank you for any help! I'm still new to R and not particularly a friend of it yet, so any tips are highly appreciated!
One relatively easy solution is to define your own custom theme based off of the theme that is used in ggsurvplot(). Looking at the documentation for the function shows us that it is applying via ggtheme= the theme theme_survminer(). We can create a custom function that uses %+replace% to overwrite one of the theme elements of interest from theme_survminer():
custom_theme <- function() {
theme_survminer() %+replace%
theme(
plot.title=element_text(hjust=0.5)
)
}
Then, you can use that theme by association with the ggtheme= argument of ggsurvplot():
library(ggplot2)
library(survminer)
require("survival")
fit<- survfit(Surv(time, status) ~ sex, data = lung)
ggsurvplot(fit, data = lung, title='Awesome Plot Title', ggtheme=custom_theme())
#Add parameters to your theme as follows
centr = theme_grey() + theme(plot.title = element_text(hjust = 0.5, face = "bold"))
#Fit the model
fit<- survfit(Surv(time, status) ~ sex, data = lung)
#create survival plot
ggsurvplot(fit, data = lung, title="Your Title Here", ggtheme=centr)

Integrate default color into personalized theme ggplot

I created my own theme and now I also want to standardize the color set that is used. I tried to do this with the list solution, provided in the answer of Viktor in this feed:
Associate a color palette with ggplot2 theme
df <- mtcars
uwvPalet <- c("#0078D2","#003282","#C4D600")
theme_uwv <- function(base_size = 22, base_family = "Verdana"){theme_hc(base_size = base_size, base_family = base_family)%+replace%theme(plot.title = element_text(color = rgb(0, 120, 210)), complete = TRUE)}
theme_uwv2 <- list(theme_uwv, scale_color_manual(values = uwvPalet))
ggplot(df, aes(fill = cyl, x = am, y = mpg)) + geom_bar(position = "dodge", stat="identity") + theme_uwv2()
Unfortunately, I get the error:
Error in theme_uwv2() : could not find function "theme_uwv2"
Anyone know how I can fix this?
The following worked for me. theme_uwv2 needed the value returned from theme_uwv() as a list element, not the function itself. Also, you were making a plot where the fill was the dominant colour variable, so I've substituted scale_color_manual() with scale_fill_manual() for demonstration purposes.
library(ggplot2)
library(ggthemes)
df <- mtcars
uwvPalet <- c("#0078D2","#003282","#C4D600")
theme_uwv <- function(base_size = 22, base_family = "Verdana"){
theme_hc(base_size = base_size, base_family = base_family) %+replace%
theme(plot.title = element_text(color = rgb(0, 120, 210, maxColorValue = 255)),
complete = TRUE)}
theme_uwv2 <- list(theme_uwv(), scale_fill_manual(values = uwvPalet))
ggplot(df, aes(fill = as.factor(cyl), x = am, y = mpg)) +
geom_col(position = "dodge") +
ggtitle("test") +
theme_uwv2

Problem with alignment of geom_point and geom_errorbar

I am trying to plot how different predictors associate with stroke and underlying phenotypes (i.e. cholesterol). In my data, I originally had working ggplot code in which shapes denoted the different variables (stroke, HDL cholesterol and total cholesterol) and colour denoted type (i.e. disease (stroke) or phenotype (HDL/total cholesterol). To make it more intuitive, I want to swap shape and colour around but now that I do this, I am having issues with position dodge and the alignment of geom_point and geom_error
stroke_graph <- ggplot(stroke,aes(y=as.numeric(stroke$test),
x=Clock,
shape = Type,
colour = Variable)) +
geom_point(data=stroke, aes(shape=Type, colour=Variable), show.legend=TRUE,
position=position_dodge(width=0.5), size = 3) +
geom_errorbar(aes(ymin = as.numeric(stroke$LCI), ymax= as.numeric(stroke$UCI)),
position = position_dodge(0.5), width = 0.05,
colour ="black")+
ylab("standardised beta/log odds")+ xlab ("")+
geom_hline(yintercept = 0, linetype = "dotted")+
theme(axis.text.x = element_text(size = 10, vjust = 0.5), legend.position = "none",
plot.title = element_text(size = 12))+
scale_y_continuous(limit = c(-0.402, 0.7))+ scale_shape_manual(values=c(15, 17, 18))+
theme(legend.position="right") + labs(shape = "Variable") + guides(shape = guide_legend(reverse=TRUE)) +
coord_flip()
stroke_graph + ggtitle("Stroke and Associated Phenotypes") + theme(plot.title = element_text(hjust = 0.5))
Graph now: 1
Previously working graph - only difference in code is swapping "Type" and "Variable": 2

Plotly Facets not translating properly

I've found that with Plotly with R, when I'm faceting plots, they often don't translate properly from R to Plotly.
For example, my graph plotted in R looks like so:
When I send it to plotly, it looks like so:
(Some data has been hidden from both plots for confidentiality reasons)
My code looks like so:
plot <- ggplot(sytoxG_data_no_NC) +
geom_ribbon(data = confidence_intervals_SG, mapping = aes(x = time_elapsed, ymin = phenotype_value.NC.lower, ymax = phenotype_value.NC.upper,
fill = "red", colour = NULL), alpha = 0.6) +
scale_fill_manual(name = "Legend",
values = c('red'),
labels = c('Negative Control')) +
xlab("Time Elapsed") +
ylab("Sytox Green") +
ggtitle("Sytox Green - Facets: Pathway") +
facet_wrap(~Pathway, ncol=6, scales = "fixed") +
theme(panel.grid = element_blank(),
axis.ticks.length = unit(0, "cm"),
panel.background = element_rect(fill = "white"),
strip.text.x = element_text(size=4),
axis.text = element_blank())
response <- py$ggplotly(plot, kwargs=list(world_readable=FALSE, filename="SG_sparklines_by_pathway", fileopt="overwrite"))
The issue might very well be with geom_ribbon rather than facets... Can you please upgrade your "plotly" package and give it another try?
I wound up using facet_grid instead of facet_wrap. Something like this:
+ facet_grid(~Pathway, scales = "free", space="free")