How to add italic values in ggplot - r

I have the following df:
df <- data.frame(Species = c("C. lupus", "C. latrans", "C. lupaster"),
pi = c('0.03', '0.04', '0.02'))
and I made a plot with ggplot
df %>%
mutate(Species= fct_reorder(Species, pi )) %>%
ggplot(aes(x=Species, y=pi)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
coord_flip() +
xlab("") +
theme_bw() +
ylab("Nucleotide diversity (π)")
How can I write the species names in italic?
Thanks!

Just add theme(axis.text.y = element_text(face = 3)):
df %>%
mutate(Species= fct_reorder(Species, pi )) %>%
ggplot(aes(x=Species, y=pi)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
coord_flip() +
xlab("") +
theme_bw() +
theme(axis.text.y = element_text(face = 3)) +
ylab("Nucleotide diversity (π)")

Related

Obtaining geom_line values at mid-month for unequally spread geom_points

I need to obtain value at 15th of every month from the geom line created using the reproducible example below. The original geom points are at varied monthly dates depending on data collection days. Appreciate any help possible
Value <- c(19.14104, 11.72115, 9.66083, 10.99109, 13.65047, 10.10627, 13.53027, 18.25272, 25.57741)
Dates <- c("07/11/19", "28/11/19", "16/12/19", "10/01/20", "21/01/20", "03/02/20", "04/03/20", "19/03/20", "20/05/20")
df <- data.frame(Value, Dates)
View(df)
df$Dates <- lubridate::dmy(df$Dates)
gpp_plot <- ggplot() +
geom_point(data = df, aes(x=Dates, y=Value), alpha=0.5) +
geom_line(data = df, aes(x=Dates, y=Value), alpha=0.5) +
theme(axis.text.y=element_text(size=10),
axis.title=element_text(size=10, , face = "bold"),
axis.text.x = element_text(size=10, face = "bold", angle = 45, vjust = 0.5))+
xlab('') +
ylab('LI-7810_FCH4_DRY_[nmol+1m-2s-1]') +
scale_x_date(date_labels = "%b %y",breaks = "1 months") +
theme(legend.position="none")
gpp_plot
As suggested in comments, you could approx the Value at new dates:
library(ggplot2)
library(lubridate)
Dates <- dmy(Dates)
NewDates <- seq(floor_date(min(Dates),'month'),floor_date(max(Dates),'month'),by='month')+days(14)
#[1] "2019-11-15" "2019-12-15" "2020-01-15" "2020-02-15" "2020-03-15" "2020-04-15" "2020-05-15"
NewValue <- approx(Dates,Value,NewDates)$y
df <- data.frame(Value=c(Value,NewValue), Dates=c(Dates,NewDates))
gpp_plot <- ggplot() +
geom_point(data = df, aes(x=Dates, y=Value), alpha=0.5) +
geom_line(data = df, aes(x=Dates, y=Value), alpha=0.5) +
theme(axis.text.y=element_text(size=10),
axis.title=element_text(size=10, , face = "bold"),
axis.text.x = element_text(size=10, face = "bold", angle = 45, vjust = 0.5))+
scale_x_date(date_labels = "%b %y",breaks = "1 months") +
ylab('LI-7810_FCH4_DRY_[nmol+1m-2s-1]') +
theme(legend.position="none")
gpp_plot

Legend label combined plots (ggplot and patchwork)

I am new to R and trying to find a simple way to change the labels of the legend for combined boxplots created with ggplot and patchwork.
I am comparing the proportions of 5 different types of cells in 2 groups (controls and asthmatic). I created boxplot for each cell type, and combined them with patchwork.
plot_mac <- ggplot(asthma_desc, aes(x=control_case, y=BAL_mac_LP, color=control_case)) +
geom_boxplot(width=0.5,lwd=0.5) +
geom_jitter(width=0.15) +
labs(y = "Macrophages %") +
stat_compare_means(label = "p.signif", label.x.npc = "center", label.y = 80, hide.ns = T)
then I do the same for 4 different types of cells.
patchwork <- plot_mac + plot_lym + plot_neu + plot_mast + plot_eos + plot_layout(guides = 'collect')
patchwork & theme_minimal() & scale_color_manual(values=c("black", "red")) &
theme(axis.title.x = element_blank(), axis.ticks.x=element_blank(), axis.text.x=element_blank(), text=element_text(size=7)) &
ylim(0,100)
I get the following plot
I would like to change the legend "control_case" to "Group", "1" to "control, "2" to "case". I could not make it work with labs(), scale_x_discrete() nor with theme().
Another option is to add a new column to your dataframe named Group.
Here is an example with mock mtcars dataset:
library(tidyverse)
library(ggpubr)
library(patchwork)
mtcars1 <- mtcars %>%
mutate(Group = case_when( am==0 ~"control",
am==1~"case",
TRUE ~ NA_character_))
p1 <- ggplot(mtcars1, aes(x=Group, y=mpg, color=Group)) +
geom_boxplot(width=0.5,lwd=0.5) +
geom_jitter(width=0.15) +
labs(y = "Macrophages %") +
stat_compare_means(label = "p.signif", label.x.npc = "center", label.y = 80, hide.ns = T)
p2 <- ggplot(mtcars1, aes(x=Group, y=wt, color=Group)) +
geom_boxplot(width=0.5,lwd=0.5) +
geom_jitter(width=0.15) +
labs(y = "Macrophages %") +
stat_compare_means(label = "p.signif", label.x.npc = "center", label.y = 80, hide.ns = T)
p3 <- ggplot(mtcars1, aes(x=Group, y=hp, color=Group)) +
geom_boxplot(width=0.5,lwd=0.5) +
geom_jitter(width=0.15) +
labs(y = "Macrophages %") +
stat_compare_means(label = "p.signif", label.x.npc = "center", label.y = 80, hide.ns = T)
patchwork <- p1 + p2 + p3 + plot_layout(guides = 'collect')
patchwork & theme_minimal() & scale_color_manual(values=c("black", "red")) &
theme(axis.title.x = element_blank(), axis.ticks.x=element_blank(), axis.text.x=element_blank(), text=element_text(size=7)) &
ylim(0,100)

how can I use special characters, superscripts or subscripts in a single label of faceted plots in ggplot2?

I would like to add superscripts and / or subscripts to only a subset of strip text labels in a faceted plot layout like this one:
conc <- runif(nrow(iris), min = 5, max = 10)
df <- iris %>% mutate(mass_area = conc/Petal.Length*Sepal.Length)
melted <- reshape2::melt(df)
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(palette = "Greens") +
theme(
legend.position = "bottom",
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank(),
strip.text = element_text(size = 12)) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free")
bp1
But mass_area should have a label in the form lab = expression("Chl concentration" ~ (mu ~ g ~ " " ~ cm^{-2}))
This response is useful but labels all facets according to the same pattern. I need to label only one.
Following the post you linked one option would be to use an ifelse to conditionally set the labels like so:
library(dplyr)
library(ggplot2)
library(hrbrthemes)
set.seed(42)
conc <- runif(nrow(iris), min = 5, max = 10)
df <- iris %>%
mutate(mass_area = conc/Petal.Length*Sepal.Length)
melted <- reshape2::melt(df) %>%
mutate(variable = ifelse(variable == "mass_area",
paste0("Chl~concentration ~ (mu ~ g ~ cm^{-2})"),
paste0(variable)))
#> Using Species as id variables
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(palette = "Greens") +
theme(
legend.position = "bottom",
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank(),
strip.text = element_text(size = 12)) +
ggtitle("mytitle") +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free", labeller = label_parsed)
bp1
Here is an approach that uses the tidyverse packages. I've used pivot_longer() instead of melt() and
case_when() instead of ifelse() just to give you a second solution, but in the end it does the same because it is a vectorised ifelse.
This gives you the same result as stefans solution.
On a side note: I've corrected the expression, so there is no space in micrograms anymore.
library(dplyr)
library(tidyr)
library(ggplot2)
conc <- runif(nrow(iris), min = 5, max = 10)
df <- iris %>% mutate(mass_area = conc/Petal.Length*Sepal.Length)
melted <- df %>% pivot_longer(cols = -Species,
names_to = "variable") %>%
mutate(variable = case_when(variable == "mass_area" ~ paste0("Chl~concentration ~ (mu*g ~ cm^{-2})"),
TRUE ~ as.character(variable))
)
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
scale_fill_brewer(palette = "Greens") +
theme(
legend.position = "bottom",
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank(),
strip.text = element_text(size = 12)) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free", label = "label_parsed")
bp1

Adjusting percentage decimals for a bar plot with facet_grid()

I have the following line:
p1 <- ggplot(mtcars, aes(x= cyl)) + geom_bar(aes(fill = vs), stat = "count") + geom_text(aes(label = scales::percent(..prop..), ymax= ..prop..), stat = "count", vjust = -0.5) + theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)
which gives this plot. This is a plot where I want to keep the count integers on the y-axis, but I want the percentages displayed above each bar.
I would like to edit the number of decimals over each bar plot. However, when using the line below:
p2 <- ggplot(mtcars, aes(x= cyl)) + geom_bar(aes(fill = vs), stat = "count") + geom_text(aes(label = scales::percent(round((..count..)/sum(..count..),1)), ymax= ((..count..)/sum(..count..))), stat="count", vjust = -.25) + theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)
The percentages are now off (see below), displaying the percentages for the whole plot, and not the separated facets. Is there a way to round the percentages without compromising the numbers?
You can use accuracy = 2 in the scales::percent function:
p1 <- ggplot(mtcars, aes(x= cyl)) + geom_bar(aes(fill = vs), stat = "count") +
geom_text(aes(label = scales::percent(..prop.., accuracy = 2), ymax= ..prop..), stat = "count", vjust = -0.5) +
theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)
p1
There is an accuracy option in scales::percent:
p1 <- ggplot(mtcars, aes(x= cyl)) +
geom_bar(aes(fill = vs), stat = "count") +
geom_text(aes(label = scales::percent(..prop..,accuracy=2)),
stat = "count", vjust = -0.5) +
theme_classic() + ylab("Count") + facet_grid(vs ~ .) + ylim(0, 15)

How do I customize the margin and label settings with plot_grid?

I would like to have the title not be chopped off and have the axis labels removed from this chart that I generated with plot_grid from cowplot.
Here is my code
data(mtcars)
library(ggplot2)
library(cowplot)
mpg = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
coord_flip()
am=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
coord_flip()
vs=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip()
gear = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip()
p=plot_grid(mpg,am,vs,gear, labels = "Variables effecting Mileage", label_size = 14, hjust = -0.5,
+ vjust = 0.5)+theme_grey()
p
Also, if it would be simpler to create this without cowplot, what do you suggest?
Here is a cowplot only answer. It might be more what you want.
library(ggplot2)
library(cowplot)
library(gtable)
data(mtcars)
mpg = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
coord_flip() + labs(x="",y="")
am=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
coord_flip()+ labs(x="",y="")
vs=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip()+ labs(x="",y="")
gear = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip()+ labs(x="",y="")
p=plot_grid(mpg,am,vs,gear) +
theme_grey() +
# Use annotation text as it is centered at the x,y point
annotate("text",x=0.5,y=1.04,size=7,label="Variables affecting Mileage") +
# Add some space around the edges
theme(plot.margin = unit(c(1,0.5,0.5,0.5), "cm"))
# Suppress tick marks
p=p+scale_y_continuous(breaks=NULL)+scale_x_continuous(breaks=NULL)
# Have to turn off clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
# need to draw it with the new clip settings
grid.draw(gt)
Yields:
would this workout for you?
library(ggplot2)
library(gridExtra)
a <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) + coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
b <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) + coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
c <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
d <- ggplot() + geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip() + theme_grey() + theme(axis.title.x = element_blank())
grid.arrange(a, b, c, d, ncol=2, top = "Variables effecting Mileage")
Thanks Mike. This does the job.
data(mtcars)
library(ggplot2)
library(cowplot)
library(gtable)
mpg = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
coord_flip() + labs(x="",y="")
am=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
coord_flip()+ labs(x="",y="")
vs=ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
coord_flip()+ labs(x="",y="")
gear = ggplot() +
geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
coord_flip()+ labs(x="",y="")
p=plot_grid(mpg,am,vs,gear,
labels = "Variables effecting Mileage",
label_size = 14, hjust = -1.3[![enter image description here][1]][1], vjust = -0.1)+
theme_grey() +
# Add some space around the edges
theme(plot.margin = unit(c(1,0.5,0.5,0.5), "cm"))
# Suppress tick marks
p=p+scale_y_continuous(breaks=NULL)+scale_x_continuous(breaks=NULL)
# Have to turn off clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
# need to draw it with the new clip settings
grid.draw(gt)
Here is my plot

Resources