Subscript letters in ggplot axis label
The reason the last one fails is that the arguments to expression
get run through the R parser and an error is returned when they fail the test of whether they could possibly be correct R syntax. The string or token 1d
is not a valid R token (or symbol). It would be possible to either break it into valid R tokens and "connect" with non-space operators, backtick it , or use ordinary quotes. I think either is a better way than using paste
:
ggplot(dat, aes(x=x,y=y)) +
geom_point() +
labs(y=expression(Blah[1*d]))
ggplot(dat, aes(x=x,y=y)) +
geom_point() +
labs(y=expression(Blah["1d"]))
Tokens (or "names" or "symbols") in R are not supposed to start with digits. So you get around that limitation by either quoting or by separating 1
and d
by a non-space separator, the *
operator. That "joins" or "ligates" a pure numeric literal with a legal R symbol or token.
To get a percent sign unsubscripted just:
ggplot(dat, aes(x=x,y=y)) +
geom_point() +
labs(y=expression(Blah[1*d]*"%"))
To put parens around the pct-sign:
expression(Blah[1*d]*"(%)")
The %
character has special meaning in R parsing, since it signifies the beginning of a user defined infix operator. So using it as a literal requires that it be quoted. The same reasoning requires that "for" and "in" be quoted, because they are in the "reserved words" group for R. There are other reserved words, (but for
and in
are the ones that trip me up most often.) Type:
?Reserved
And another "trick" is to use quotation marks around digits within italic()
if you need them italicized. Unquoted digits do not get italicized inside that function.
Caveats: paste
is a plotmath function except it has different semantics than the base::paste function
. In particular, it has no 'sep' argument. So you can never get a space between the printed arguments and if you try to put in a non-space item, a single instance will appear after all the other arguments labeled as sep=" "
.
paste0
is not a plotmath function and so will not get interpreted but rather will appear "unprocessed" with its unprocessed arguments inside parentheses.
ggplot2 axis text label: subscript + superscript + square brackets
You could use expression
:
library(ggplot2)
ggplot(mtcars, aes(hp, mpg)) +
geom_point() +
labs(y = expression("S"["in"] ~ "[W" ~ m^-2~"]"))
Superscript in axis labels in ggplot2 for ions
Try to put the superscript as a literal, between quotes.
g <- ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot()
g + xlab(bquote('Superscript as a literal' ~~ Ca^'2+'))
Subscripts and superscripts - or + with ggplot2 axis labels? (ionic chemical notation)
Try quoting the minus sign after the superscript operator:
ggplot(df, aes(x=x, y=y))+
geom_point(size=4)+
labs(x=expression(Production~rate~" "~mu~moles~NO[3]^{"-"}-N~Kg^{-1}),
y=expression(Concentration~mg~L^{-1})) +
theme(legend.title = element_text(size=12, face="bold"),
legend.text=element_text(size=12),
axis.text=element_text(size=12),
axis.title = element_text(color="black", face="bold", size=18))
I think it looks more scientifically accurate to use the %.%
operator between units:
+ labs(x=expression(Production~rate~" "~mu~moles~NO[3]^{textstyle("-")}-N %.% Kg^{-1}),
y=expression(Concentration~mg~L^{-1})) +
textstyle
should keep the superscript-ed text from being reduced in size. I'm also not sure why you have a " "
between two tildes. You can string a whole bunch of tildes together to increase "spaces":
ggplot(df, aes(x=x, y=y))+
geom_point(size=4)+
labs(x=expression(Production~rate~~~~~~~~~~~~mu~moles~NO[3]^{textstyle("-")}-N %.% Kg^{-1}),
y=expression(Concentration~mg~L^{-1})) +
theme(legend.title = element_text(size=12, face="bold"),
legend.text=element_text(size=12),
axis.text=element_text(size=12),
axis.title = element_text(color="black", face="bold", size=18))
And a bonus plotmath tip: Quoting numbers is a way to get around the documented difficulty in producing italicized digits with plotmath. (Using italic(123)
does not succeed, ... but italic("123")
does.)
Using subscript and italics in ggplot2 axis labels
The easiest way to format without using the expression
method is to use simple html.
I recommend the ggtext
package
see also this answer regarding Greek text in ggplot2
library(tidyverse)
library(ggtext) #
mtcars %>%
ggplot() +
geom_histogram(aes(drat), bins = 20) +
labs(x="K<sub><i>D</i></sub>(\u00b5M)") +
theme(axis.title.x = element_markdown())
Created on 2021-04-29 by the reprex package (v2.0.0)
How to get a subscript into an axis title in `ggplot`
Is this something you want?
set.seed(4)
x <- runif(20, 5, 10)
y <- runif(20, 15, 20)
df <- data.frame(x,y)
ggplot()+
geom_point(data=df, aes(x,y))+
labs(y = expression(paste('Ba:Ca (µmol:mol'^-1,')')), x = "x axis")
Line-break and superscript in axis label ggplot2 R
You could use expression()
and atop()
to autoformat white space.
ggplot(data,aes(x=x,y=y)) +
geom_point() +
xlab( expression(atop("Density of mobile",paste("invertebrates (ind.~",m^{2},")"))))
Data
set.seed(1)
data <- data.frame(x = 1:10, y = 1:10 + runif(-1,1,n=10))
how can I use special characters, superscripts or subscripts in a single label of faceted plots in ggplot2?
Here is an approach that uses the tidyverse packages. I've used pivot_longer()
instead of melt()
andcase_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
How to type subscript/superscript in the category labels in bar plot?
This could be achieved by passing scales::parse_format
to the labels argument of the scale. Using ?plotmath
notation you have to recode your categories as e.g. K[b]
to get a subscript "b":
df <- data.frame(
x = paste0("K[", letters[1:3], "]"),
y = 1:3
)
library(ggplot2)
ggplot(df, aes(x, y)) +
geom_col() +
scale_x_discrete(labels = scales::parse_format())
Related Topics
Remove Empty Documents from Documenttermmatrix in R Topicmodels
How to Deal with "Data of Class Uneval" Error from Ggplot2
Finding Row Index Containing Maximum Value Using R
How to Convert Data Frame to Spatial Coordinates
How to Maintain Size of Ggplot with Long Labels
Dplyr Issues When Using Group_By(Multiple Variables)
Using Parallel's Parlapply: Unable to Access Variables Within Parallel Code
How to Disable "Save Workspace Image" Prompt in R
Grid of Multiple Ggplot2 Plots Which Have Been Made in a for Loop
Can Sweave Produce Many PDFs Automatically
Delete Duplicate Rows in Two Columns Simultaneously
Split Data Frame into Rows of Fixed Size
Fixing Cluttered Titles on Graphs
How to Specify a Dynamic Position for the Start of Substring
Tidyr How to Spread into Count of Occurrence