Adjust title vertically to inside the plot - vjust not working - r

I want to place the title inside the plot instead at the default top position.
Here is a simple code snippet
library(ggplot2)
df <- data.frame(x = c(1:10), y = rnorm(10, 1, 2))
ggplot(df, aes(x, y))+
geom_line() +
ggtitle("Demo") +
theme(plot.title = element_text(vjust = -3))
In the past I was able to do this by varying vjust value, but now it is not working. Any idea how to do this?

In the ggplot issue "vjust not working in v 2.0 for plot.title?", Hadley writes:
"All text elements now have a margin, which by default scale with the font
size in the theme. This leads to nicer spacing, particularly at large font
sizes. This means hacks with vjust and hjust no longer work. Instead,
use the margin() parameter of element_text()"
Play around with the t and b arguments in margin to adjust the title, e.g.:
ggplot(df, aes(x, y))+
geom_line() +
ggtitle("Demo") +
theme(plot.title = element_text(margin = margin(t = 10, b = -20)))
See ?margin for further arguments.
Note that you should use the margin argument for axis.title.x and axis.title.y as well:
ggplot() + ggtitle("this is title") + xlab("this is x") + ylab("this is y") +
theme(plot.title = element_text(margin = margin(b = -10)),
axis.title.x = element_text(margin = margin(t = -10)),
axis.title.y = element_text(margin = margin(r = -10)))

Related

Plot legend to move left ggplot

I like to move the legend a bit further on the left But I am not getting how to do it.
Secondly, I also want to reduce the space between axis label and legend too
Can you please suggest something
the code is given below that I am using
The image of the graph is in the link below
"tooltip"
ggplot(Q6_m, aes( choice,temp,fill=Answer ))+
geom_bar(position = position_stack(reverse = TRUE), stat="identity") +
coord_flip() +
xlab("") +
ylab("Number of responses") +
scale_fill_brewer(type = "div") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8,face="bold"), legend.title = element_blank(),
legend.text=element_text(size=7)) +
ggtitle("Q6:Rate your ability to perform the following procedures WITHOUT attending assistance?")+
theme(plot.title = element_text(color = "black", size = 7.5, face = "bold", hjust = 1))+
facet_wrap(~gender,scales = "free_x")+
theme(legend.position="bottom", legend.direction = "horizontal",legend.key.size = unit(0.5,"line")
)
You should use legend.justification to get the legend on the left side of the plot and legend.margin to reduce the space between axis labels and the legend:
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species))+
geom_boxplot()+
theme(legend.position = "bottom",
legend.justification = c(0,1),
legend.margin = margin(t = -15, r = 0, b = 0, l = 0, unit = "pt"))
Does it answer your question ?

Plot axis name on a different position other than the middle of the axis

I would like to use ggplot to plot a graph that looks similar to this, where the axis names (represented as the units) are shown along the axes instead of right in the middle of the axes.
The only R way I can think of is to add a text object, but that may causes alignment inconsistencies if I want to display a few similar graphs together. Editing after the figure has been produced also does not seem elegant because the same editing software's font (say ppt editors) may not look the same as the same font in R.
Is there another way to achieve this? Thanks in advance!
This is what worked for me.
library(ggplot2)
base <- ggplot(economics, aes(date, psavert)) +
geom_blank() +
labs(x="KG", y="%")
base + theme(axis.title.y = element_text(hjust = 1, size = 14), axis.title.x = element_text( hjust = 1, size = 14))
The default values for axis.title.y = element_text( hjust = .5) and axis.title.x = element_text( hjust = .5), and changing the hjust to 0 will bring the axis texts to the co-ordinate point (0,0).
Update
To replicate the background and the arrow, you can do as follows:
# see ?ggplot2::arrow
arrow <- arrow(length = unit(0.5, "cm"), ends = "last", type = "closed")
# -------------------------------------------------------------------------
# A reproducible dataset from ggplot2 (you can use your own data set)
base <- ggplot(economics, aes(date, psavert)) +
geom_blank() +
labs(x="Kg", y="%") +
theme_bw()
# -------------------------------------------------------------------------
# Add a theme layer removing boarder, grid lines and add the axes arrow
base_bg <- base + theme(
panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(arrow = arrow)
)
# -------------------------------------------------------------------------
# finally position the axis title up to the arrow
base_bg + theme(axis.title.y = element_text(hjust = 1, size = 14, face="bold", family = "TT Times New Roman"), axis.title.x = element_text( hjust = 1, size = 14, face = "bold", family="Serif"))
Output
Update - correcting % on Y-axis
#see the addition of angle = 360 on axis.title.y
base_bg + theme(axis.title.y = element_text(hjust = 1, size = 14, face="bold", family = "TT Times New Roman", angle = 360), axis.title.x = element_text( hjust = 1, size = 14, face = "bold", family="Serif"))
Output - label '%' corrected
try:
mop + theme(axis.text.x = element_text(margin=margin(1,2,3,4,"pt"),angle=0)
where 1,2,3,4 indicates the measurements of bottom, left, top, right margins
You can use hjust to move the axis label along the line, with 1 being the max.
p + theme(axis.title.x = element_text(hjust = 1), axis.title.y = element_text(hjust = 1, angle = 0))

How can I adjust the vertical spacing of font and axis title in ggplot2? [duplicate]

I want to place the title inside the plot instead at the default top position.
Here is a simple code snippet
library(ggplot2)
df <- data.frame(x = c(1:10), y = rnorm(10, 1, 2))
ggplot(df, aes(x, y))+
geom_line() +
ggtitle("Demo") +
theme(plot.title = element_text(vjust = -3))
In the past I was able to do this by varying vjust value, but now it is not working. Any idea how to do this?
In the ggplot issue "vjust not working in v 2.0 for plot.title?", Hadley writes:
"All text elements now have a margin, which by default scale with the font
size in the theme. This leads to nicer spacing, particularly at large font
sizes. This means hacks with vjust and hjust no longer work. Instead,
use the margin() parameter of element_text()"
Play around with the t and b arguments in margin to adjust the title, e.g.:
ggplot(df, aes(x, y))+
geom_line() +
ggtitle("Demo") +
theme(plot.title = element_text(margin = margin(t = 10, b = -20)))
See ?margin for further arguments.
Note that you should use the margin argument for axis.title.x and axis.title.y as well:
ggplot() + ggtitle("this is title") + xlab("this is x") + ylab("this is y") +
theme(plot.title = element_text(margin = margin(b = -10)),
axis.title.x = element_text(margin = margin(t = -10)),
axis.title.y = element_text(margin = margin(r = -10)))

Extending plot window beyond x-axis labels in ggplot

In ggplot I have a graph whose x-axis labels extend beyond the plot window in RStudio even if I try to export the picture and no matter how wide I make the picture. Below is my current solution using limits in scale_x_continuous. Is it possible to have the picture extend so that I can capture my last x-axis label (i.e., 25021643) but without having the line segment extend?
Code to reproduce above:
library(ggplot2)
p <-
ggplot(NULL) +
xlab("x-axis") +
theme_bw() +
scale_x_continuous(breaks = as.integer(seq(0,25021643,(25021643/4))), limits=c(0,26021643),labels = as.integer(seq(0,25021643,(25021643/4))), expand = c(0,0)) +
scale_y_continuous(limits = c(-1, (nrow(chr5)+1)), expand = c(0,0)) +
geom_hline(yintercept = -1) +
geom_segment(aes(x = 0, y = -1, xend = 0, yend = -0.9)) +
geom_segment(aes(x = 25021643, y = -1, xend = 25021643, yend = -0.9)) +
theme(panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.border=element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.x = element_line(size=1),
axis.title.x = element_text(size=20),
axis.text.x = element_text(size=20))
p
Adding plot.margin=unit(c(0,20,0,0),"mm") seemed to do the job.
You may also use:
plot.margin = margin(r = 20, unit = "mm")
Just another way of doing the same thing, but avoiding writing the values for all sides of the plot: 't' is top, 'r' is right, 'l' is left, and 'b' is bottom. You can write all or any sides you wish separated by a comma:
plot.margin = margin(r = 20, l = 30, b = 15, t = 40, unit = "mm")
or, if you wish to use standard units ('pt'):
plot.margin = margin(r = 20)

ggplot2, change title size

I would like to have my main title and axis title have the same font size as the annotated text in my plot.
i used theme_get() and found that text size is 12, so I did that in my theme statement - this did not work. I also tried to send the relative size to 1, and this did not work
I was hoping someone could please help me.
Code is below
library(ggplot2)
library(gridExtra) #to set up plot grid
library(stringr) #string formatting functions
library(plyr) #rbind.fill function
library(reshape2) #transformation of tables
dat<-data.frame(
est=c(2.75,2.95,2.86,2.99),
ucl=c(2.92,3.23,3.38,4.91),
lcl=c(2.24,1.67,2.44,1.82),
ord=c(1,2,1,2)
)
dat$varname<-c('Estimate','Predictive','Estimate','Predictive')
dat$grp<-c('Cobalt','Cobalt','Chromium','Chromium')
for (i in unique(dat$grp)) {
dat <- rbind.fill(dat, data.frame(grp = i, ord=0,
stringsAsFactors = F))
}
dat$grp_combo <- factor(paste(dat$grp, dat$ord, sep = ", "))
dat$grpN <- as.numeric(dat$grp_combo)
rng <- c(0,6)
scale.rng <-1
xstart=-(max(dat$grpN)+2)
xend=4
ThemeMain<-theme(legend.position = "none", plot.margin = unit(c(0,0,0, 0), "npc"),
panel.margin = unit(c(0,0, 0, 0), "npc"),
title =element_text(size=12, face='bold'),
axis.text.y = element_blank(),
axis.text.x = element_text(color='black'),
axis.ticks.y = element_blank(),
axis.title.x = element_text(size=12,color='black',face='bold')
)
BlankSettings <- theme(legend.position = "none",
title =element_text(size=12, face='bold'),
plot.margin = unit(c(0,0, 0, 0), "npc"),
panel.margin = unit(c(0,0, 0, 0), "npc"),
axis.text.x = element_text(color='white'),
axis.text.y = element_blank(),
axis.ticks.x = element_line(color = "white"),
axis.ticks.y=element_blank(),
axis.title.x = element_text(size=12,color='white',face='bold'),
panel.grid = element_blank(),panel.grid.major = element_blank(),panel.background = element_blank()
)
pd <- position_dodge(width = 0.7)
#######################################################################################################
#MAIN PLOT
#######################################################################################################
mainPart<-
ggplot(dat, aes(x=-grpN,y=est, ymin=lcl, ymax=ucl, group=1)) +
scale_y_continuous(name=NULL, breaks=seq(rng[1], rng[2], scale.rng), limits=c(rng[1], rng[2]), expand=c(0,0)) +
ylab('Ion Concentration') +
ggtitle('Mean with 95% HDI')+
#geom_segment(aes(x=xstart, xend=0, y=0, yend=0), linetype=3, alpha=0.01) +
geom_linerange(aes(linetype="1"),position=pd) +
geom_point(aes(shape="1"), fill="white",position=pd) +
coord_flip() +
scale_x_continuous(limits=c(xstart,xend), expand=c(0,0))+xlab(NULL)+
ThemeMain
#######################################################################################################
#varnameS
#######################################################################################################
# ystart & yend are arbitrary. [0, 1] is
# convinient for setting relative coordinates of
# columns
ystart = 0
yend = 1
p1 <-
ggplot(dat, aes(x = -varnameN, y = 0)) +
coord_flip() +
scale_y_continuous(limits = c(ystart, yend)) +
BlankSettings+
scale_x_continuous(limits = c(xstart, xend), expand = c(0, 0)) +
xlab(NULL) +
ylab('') +
ggtitle('')
studyList<-
p1 +
with(unique(dat[is.na(dat$varname),c("grpN","grp")]), annotate("text",label=grp, x=-grpN,y=0, fontface='bold', hjust=0)) + #Variable Group varnames
with(dat[!is.na(dat$var),],annotate("text",label=varname,x=-grpN,y=0.04, hjust=0)) #Variables
#######################################################################################################
#EFFECTS
#######################################################################################################
f<-function(x) round(x,2)
dat$msmt<-paste(f(dat$est),' [',f(dat$lcl),', ',f(dat$ucl),']',sep='')
effectSizes<-p1+
annotate("text",x=-dat$grpN, y=0.25,label=ifelse(is.na(dat$varname)==T,'',dat$msmt))
grid.arrange(ggplotGrob(studyList), ggplotGrob(mainPart),
ggplotGrob(effectSizes), ncol = 3, widths = unit(c(0.19,
0.4, 0.41), "npc"))
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
Using the theme with plot.title is the easiest way. But there is another option using ggtext which provides Markdown (element_markdown) and HTML rendering for ggplot2. So you can use HTML tags to change the "font-size" of the title for example. The advantage of this is that you can change parts of title easily, so you can give certain parts of the title a different font-size or colors using HTML tags.
Here is a reproducible example:
library(ggplot2)
library(ggtext)
# font size using html
ggplot(mtcars, aes(x = cyl)) +
geom_bar() +
ggtitle("<span style='font-size: 22pt;'>This is bigger text</font>") +
theme(plot.title = element_markdown())
# Change parts of title font size
ggplot(mtcars, aes(x = cyl)) +
geom_bar() +
ggtitle("<span style='font-size: 22pt;'>This is bigger text,</font>
<span style='font-size: 10pt;'>This is smaller text.</font>") +
theme(plot.title = element_markdown())
Created on 2022-08-24 with reprex v2.0.2
As you can see, the title has two different font-sizes. For extra information and examples you can check the link above.

Resources