r ggplot use plotmath expressions dynamically - r

I want to change axis labels dynamically using ggplot. The code below is a simple version of what I'd like to do. It correctly displays a degree symbol in the y axis.The commented out ylab lines of code are what I'd like to do but fail. I want to create the plotmath code, assign it to a variable (e.g. yLabel) and then have ggplot interpret it.
library(data.table)
library(ggplot2)
DT <- data.table(timeStamp=c(1:12), ColN1=runif(12, 0, 10))
DT.long <- data.table::melt(
DT, id.vars = c("timeStamp"))
yLabel <- "Temperature~(~degree~F)"
yLabel1 <- expression("Temperature~(~degree~F)")
p <- ggplot(data = DT.long, aes(x = timeStamp, y = value)) +
xlab("Time") +
# ylab( expression(paste("Value is ", yLabel,","))) +
# ylab(yLabel) +
# ylab(yLabel1) +
ylab(Temperature~(~degree~F)) +
scale_y_continuous() +
theme_bw() +
geom_line()
print(p)

Use bquote
Here is your dynamic component
temp <- 12
Assign it to the label using
ylab(bquote(Temperature ~is ~ .(temp) ~(degree~F)))
Or to address your additional question below
V = "Temperature is ("~degree~"F)"
W = "depth is ("~degree~"C)"
ggplot(data = DT.long, aes(x = timeStamp, y = value)) +
xlab("Time") +
ylab(bquote(.(V)))
ggplot(data = DT.long, aes(x = timeStamp, y = value)) +
xlab("Time") +
ylab(bquote(.(W)))

I had the same issue with dynamically modifying an axis label and B Williams answer helped me.
The solution:
dynamic <- "dynamic text"
# Put the dynamic text in its right context
str <- sprintf("Static label text [%s]", dynamic)
# Use multiplication "*" rather than "~" to build the expression to avoid unnecessary space
complete_label <- bquote(.(str)[subscript]*"/L")
To verify that it works:
library(ggplot2)
ggplot() + labs(x = complete_label)

Related

Axis label specifications in ggplot

I'm attempting to have a two-line y-axis label that contains a superscript in ggplot and I am struggling.
I want the y axis label to say “[3H]ASEM binding (pmol/g)” with the 3 superscripted and (pmol/g) on a separate line.
This is what I have tried so far:
labs(x="", y=expression(paste("[" ^3 "H] ASEM Binding \n (pmol/g)")))
And it's given me the error "unexpected string constant"
Any suggestions?
You need an empty ''(2 single quotes) prior to the ^3.
ggplot(sample_data, aes(x, y)) +
geom_point() +
labs(
x = "",
y = expression(atop(paste("[", ''^3, "H] ASEM Binding"), "(pmol/g)"))
)
Another alternative is:
y = expression(atop("["^3*"H] ASEM Binding", "(pmol/g)"))
I'm not quite sure what you're doing with your for loop, but this code chunk should get you the two-lined axis label with a superscript for which you are looking.
library(tidyverse)
sample_data <- tibble(x = rnorm(1000),
y = x^2)
sample_data %>%
ggplot(aes(x, y)) +
geom_point() +
labs(
x = "X",
y = expression(atop("Variable", X^2))
)
Is this what you are after?
library(ggplot2)
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point()+
labs(x = "",
y = expression(atop("[ "^3*H~"] ASEM Binding", "(pmol/g)")))+
theme(plot.margin = unit(c(10, 10, 20, 10), "mm"))
Created on 2020-05-19 by the reprex package (v0.3.0)

Display Greek symbols and charge facet titles at the same time with ggplot

I know how to modify titles in ggplot without altering the original data. Suppose I have the following data frame and I want to change the labels. Then, I would do so in the following way
df <- data.frame(x = 1:4, y = 1:4, label = c(c("params[1]", "params[2]", "params[3]",
"params[4]")))
params_names <- list(
'params[1]'= "beta[11]",
'params[2]'= "beta[22]",
'params[3]'= "beta[33]",
'params[4]'= "beta[44]"
)
param_labeller <- function(variable, value){
params_names[value]
}
ggplot(df, aes(x=x,y=y)) +
geom_point() +
facet_grid(~label, labeller = param_labeller)
If I wanted to display the subscripts, I would just do this
ggplot(df, aes(x=x,y=y)) +
geom_point() +
facet_grid(~label, labeller = label_parsed)
How do I apply both operations at the same time?
I don't know exactly if this conflicts with you not wanting to "alter" the original data, but you add the labelling information to the factor itself:
df$label2 <- factor(df$label,
labels = c("beta[4]", "beta[24]", "beta[42]", "beta[43]"))
ggplot(df, aes(x = x, y = y)) +
geom_point() +
facet_grid( ~ label2, labeller = label_parsed)
This produces the following plot:
Plot with formatted facet labels

Adding specific labels to legend

Goal: add numeric labels(number of bar on the plot) to legend, e.g 1.Company X
2.Company Y
3.Company Z
library(ggplot2)
require(scales)
companies = c('Company X','Company Y','Company Z')
profits = c(100,200,300)
data1 = data.frame(companies,profits)
CP <- ggplot(data1, aes(x = data1$companies,y = data1$profits,fill =data1$companies )) +
geom_bar(stat = 'identity') +
scale_x_discrete(name = "Companies",labels = 1:length(data1$companies))
Currently I have
What you might be looking for is paste:
newcompanies <- paste(1:50,companies,sep=".")
Personal (style) suggestion:
Search how you can change the colours to one colour-range. For fifty companies this colour-range will be confusing.
You can use seq_along and paste to make the plot you want as follow:
ggplot(data1, aes(x=seq_along(companies), weight=profits,
fill=paste(seq_along(companies), companies))) +
geom_bar() +
scale_fill_discrete("Companies") +
labs(x="Company Labels", y="Count")

How to underline text in a plot title or label? (ggplot2)

Please pardon my ignorance if this is a simple question, but I can't seem to figure out how to underline any part of a plot title. I'm using ggplot2.
The best I could find was
annotate("segment") done by hand, and I have created a toy plot to illustrate its method.
df <- data.frame(x = 1:10, y = 1:10)
rngx <- 0.5 * range(df$x)[2] # store mid-point of plot based on x-axis value
rngy <- 0.5 * range(df$y)[2] # stores mid-point of y-axis for use in ggplot
ggplot(df, aes(x = x, y = y)) +
geom_point() +
ggtitle("Oh how I wish for ..." ) +
ggplot2::annotate("text", x = rngx, y = max(df$y) + 1, label = "underlining!", color = "red") +
# create underline:
ggplot2::annotate("segment", x = rngx-0.8, xend = rngx + 0.8, y= 10.1, yend=10.1)
uses bquote(underline() with base R
pertains to lines over and under nodes on a graph
uses plotmath and offers a workaround, but it didn't help
Try this:
ggplot(df, aes(x = x, y = y)) + geom_point() +
ggtitle(expression(paste("Oh how I wish for ", underline(underlining))))
Alternatively, as BondedDust points out in the comments, you can avoid the paste() call entirely, but watch out for the for:
ggplot(df, aes(x = x, y = y)) + geom_point() +
ggtitle(expression(Oh~how~I~wish~'for'~underline(underlining)))
Or another, even shorter approach suggested by baptiste that doesn't use expression, paste(), or the many tildes:
ggplot(df, aes(x = x, y = y)) + geom_point() +
ggtitle(~"Oh how I wish for "*underline(underlining))

How to use subscripts in ggplot2 legends [R]

Can I use subscripts in ggplot2 legends? I see this question on greek letters in legends and elsewhere, but I can't figure out how to adapt it.
I thought that using expression(), which works in axis labels, would do the trick. But my attempt below fails. Thanks!
library(ggplot2)
temp <- data.frame(a = rep(1:4, each = 100), b = rnorm(4 * 100), c = 1 + rnorm(4 * 100))
names(temp)[2:3] <- c("expression(b[1])", "expression(c[1])")
temp.m <- melt(temp, id.vars = "a")
ggplot(temp.m, aes(x = value, linetype = variable)) + geom_density() + facet_wrap(~ a)
The following should work (remove your line with names(temp) <-...):
ggplot(temp.m, aes(x = value, linetype = variable)) +
geom_density() + facet_wrap(~ a) +
scale_linetype_discrete(breaks=levels(temp.m$variable),
labels=c(expression(b[1]), expression(c[1])))
See help(scale_linetype_discrete) for available customization (e.g. legend title via name=).
If you want to incorporate Greek symbols etc. into the major tick labels, use an unevaluated expression.
For a bar graph, i did the following:
library(ggplot2)
data <- data.frame(names=tolower(LETTERS[1:4]),mean_p=runif(4))
p <- ggplot(data,aes(x=names,y=mean_p))
p <- p + geom_bar(colour="black",fill="white")
p <- p + xlab("expressions") + scale_y_continuous(expression(paste("Wacky Data")))
p <- p + scale_x_discrete(labels=c(a=expression(paste(Delta^2)),
b=expression(paste(q^n)),
c=expression(log(z)),
d=expression(paste(omega / (x + 13)^2))))
p

Resources