ggplot2, change title size - r

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.

Related

Increase Vertical Spacing between Legend Key in ggplot2

How can I increase vertical spacing between legend keys:
p1 <- ggplot(data = HSS, mapping = aes(x = EVENT, y = HSS, fill = TIME)) +
geom_bar(stat = "identity",width=0.7, colour = "black", position = position_dodge(0.7)) +
scale_fill_manual("HSS", values = c("deepskyblue3", "indianred2"),
labels = c("1200 UTC (0.049)", "0000 UTC (0.031)")) + theme_bw()
p1 <- p1 + scale_y_continuous(expand = expansion(mult = c(0.0085, -0.085)),
limits = c(-0.03,0.5), breaks = c(-0.03,-0.01, 0.01, 0.03, 0.05, 0.07,0.09,0.11,0.13,0.15,0.17,
0.19, 0.21,0.23,0.25,0.27,0.29,0.31,0.33,0.45),
labels = c("-0.03","-0.01","0.01","0.03","0.05","0.07","0.09","0.11","0.13","0.15","0.17",
"0.19","0.21","0.23","0.25","0.27","0.29","0.31","0.33","0.45")) +
theme(axis.text.x=element_text(color = "black", size=12, face = "bold", angle=90, vjust=.5,
hjust=0.8)) +
theme(axis.text.y = element_text(color = "black", size=12, face = "bold"))
p1 <- p1 + theme( axis.line = element_line(colour = "black", size = 0.5, linetype = "solid")) +
labs( y = "HSS")
p1 <- p1 + theme(axis.title=element_text(colour = "blue2" ,size=14,face="bold", vjust = 0.1))
p1 <- p1 + theme(legend.position=c(0.98,0.98)) + theme(legend.title=element_blank(),
legend.text = element_text(face = "bold", size = "12"),
legend.box.background = element_rect(size=0.7, linetype="solid"),
legend.justification = c("right", "top"),
legend.box.margin = margin(1, 1, 1, 1)
)
p1
I tried using legend.key.height legend.spacing.y guide but it only stretched legend keys without adding space between them. Also how can I remove alternate lables (encircled) of Y-axis keeping tickmark with plot.
After browsing ggplot2's source code for a bit, I come to the conclusion that the legend.spacing.y is only applied when the byrow = TRUE as argument to the legend.
Simplied example below.
library(ggplot2)
ggplot(iris, aes(Sepal.Width)) +
geom_density(aes(fill = Species)) +
guides(fill = guide_legend(byrow = TRUE)) +
theme(legend.spacing.y = unit(1, "cm"))
With regards to the labels, just remove the values from the breaks argument in scale_y_continuous() that you don't want to show, you're already specifying them manually.

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 ?

How to put plots without any space using plot_grid?

I'm doing an arrangement of 2x2 plots. The plots share the same axis, so I want to put them together, e.g.
This code:
library(ggplot2)
library(cowplot)
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
plot <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme(aspect.ratio = 0.5)
plot_grid(plot, plot, plot, plot, align = "hv", ncol = 2)
produces
But I'd like something like:
How can I achieve a similar result?
I think this is a case for the ggarrange() function from the egg package. Doing this with plot_grid() would require endless fiddling and isn't worth it.
(The technical reason is that plot_grid() keeps the total area for each plot in the grid constant, but if some plots have an x axis and others don’t then they take up different areas. One could try to circumvent this by using the rel_heights argument but there’s no good way to calculate the correct values for rel_heights, so it would be trial and error. By contrast, ggarrange() separately looks at the plot panel and the surrounding elements and makes sure the plot panels have the same size.)
Here is the code using ggarrange():
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
pbase <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_bw()
ptopleft <- pbase +
scale_x_continuous(position = "top") +
theme(plot.margin = margin(5.5, 0, 0, 5.5),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
ptopright <- pbase +
scale_y_continuous(position = "right") +
scale_x_continuous(position = "top") +
theme(plot.margin = margin(5.5, 5.5, 0, 0),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
pbottomleft <- pbase +
theme(plot.margin = margin(0, 0, 5.5, 5.5))
pbottomright <- pbase +
scale_y_continuous(position = "right") +
theme(plot.margin = margin(0, 5.5, 5.5, 0))
library(egg)
ggarrange(ptopleft, ptopright,
pbottomleft, pbottomright,
ncol = 2)
Two comments:
To remove every last bit of space below the plot panel on the top plots, we need to move the x axis to the top, even though we're not showing it. This is a strange limitation of the theming mechanism. We can't fully get rid of just one axis.
I'm not a big fan of shared axis titles, as in your example. I think each axis should have a title. If you want shared axis titles, why not use the faceting mechanism?
You can set subtle plot.margin each plot, then grid.arrange and add labs.
library(ggplot2)
library(grid)
library(gridExtra)
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
plot1 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.text.x = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(5.5, 5.8, -50, 5.5), "pt"))
plot2 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.text.x = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(5.5, 5.5, -50, 5.5), "pt")) +
scale_y_continuous(position = "right")
plot3 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(-50, 5.8, -50, 5.5), "pt"))
plot4 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(-50, 5.5, -50, 5.5), "pt")) +
scale_y_continuous(position = "right")
grid.arrange(grobs = list(plot1, plot2, plot3, plot4), ncol = 2, bottom = 'Index', left = 'Value', right = 'Value')
final plot

geom_tile and facet_grid/facet_wrap for same height of tiles

Using ggplot, I would like represent a graph tile with panel, but with same height tile for each panel.
I have this graph :
dataSta <- list(sites=rep(paste("S", 1:31),each=12), month=rep(1:12,31), value=round(runif(31*12, min=0, max=3000)), panel=c(rep("Group 1",16*12),rep("Group 2", 12*12), rep("Group 3", 3*12)))
library(ggplot2)
library(grid)
base_size <- 9
windows()
ggplot(data.frame(dataSta), aes(factor(month), sites)) +
geom_tile(aes(fill = value), colour = "black")+
facet_wrap(~panel, scale="free_y", nrow=3)+
theme_grey(base_size = base_size) +
labs(x = "",y = "") +
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(legend.title = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(size = base_size *0.8, hjust = 0),
panel.margin = unit(0,"lines"),
strip.text = element_text(colour="red3", size=10, face=2))
But height of tiles is different between panel. I try to use facet_grid :
windows()
ggplot(data.frame(dataSta), aes(factor(month), sites)) +
geom_tile(aes(fill = value), colour = "black")+
facet_grid(panel~., scales="free_y", space="free")+
theme_grey(base_size = base_size) +
labs(x = "",y = "") +
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(legend.title = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(size = base_size *0.8, hjust = 0),
panel.margin = unit(0,"lines"),
strip.text = element_text(colour="red3", size=10, face=2))
The problem with height of tiles is resolved, but labels of panel (Group 1 ... Group 3) are not on top of panel. Is it possible to change position of panel labels with facet_grid ? or combine facet_grid and facet_wrap ?
Thanks for your help, and sorry for my English !
You can look at what ggplot contains before plotting, and rescale the panels accordingly.
g <- ggplot_build(p)
## find out how many y-breaks are in each panel
## to infer the number of tiles
vtiles <- sapply(lapply(g$panel$ranges, "[[", "y.major"), length)
## convert the plot to a gtable object
gt <- ggplot_gtable(g)
## find out which items in the layout correspond to the panels
## we refer to the "t" (top) index of the layout
panels <- gt$layout$t[grepl("panel", gt$layout$name)]
## replace the default panel heights (1null) with relative sizes
## null units scale relative to each other, so we scale with the number of tiles
gt$heights[panels] <-lapply(vtiles, unit, "null")
## draw on a clean slate
library(grid)
grid.newpage()
grid.draw(gt)
It took me some time to find easier solution which is actually part of the facet_grid where you can set the space = "free_y". More info at recent question.
The ggforce package has a neat little function for this called facet_col. It requires no messing around with the grid package!
All you have to do is replace the call to facet_grid with the appropriate facet_col alternative:
library(ggplot2)
library(ggforce)
dataSta <- list(sites=rep(paste("S", 1:31),each=12),
month=rep(1:12,31), value=round(runif(31*12, min=0, max=3000)),
panel=c(rep("Group 1",16*12),rep("Group 2", 12*12), rep("Group 3", 3*12)))
base_size <- 9
ggplot(data.frame(dataSta), aes(factor(month), sites)) +
geom_tile(aes(fill = value), colour = "black") +
# Here's the line to alter:
facet_col(vars(panel), , scales = "free_y", space = "free") +
theme_grey(base_size = base_size) +
labs(x = "",y = "") +
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(legend.title = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(size = base_size *0.8, hjust = 0),
panel.spacing = unit(0,"lines"),
strip.text = element_text(colour="red3", size=10, face=2))

R stacked bar graph plotting geom_text

I'm trying to plot a stacked bar graph in R using ggplot. I also want to include percentage in each piece of bars for that piece. I tried to follow the posts 1, 2, 3 but the values are not exactly in their respective blocks. My data is a file in dropbox.
My code is as follows:
f<-read.table("Input.txt", sep="\t", header=TRUE)
ggplot(data=f, aes(x=Form, y=Percentage, fill=Position)) +
geom_bar(stat="identity", colour="black") +
geom_text(position="stack", aes(x=Form, y=Percentage, ymax=Percentage, label=Percentage, hjust=0.5)) +
facet_grid(Sample_name ~ Sample_type, scales="free", space="free") +
opts(title = "Input_profile",
axis.text.x = theme_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = theme_text(face="bold", size=11),
axis.title.x = theme_text(face="bold", size=9),
axis.title.y = theme_text(face="bold", size=9, angle=90),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank()) +
scale_fill_hue(c=45, l=80)
ggsave("Output.pdf")
The output is-
Any help is greatly appreciated.
Thank you for your help and time!
I think you're using an older version of ggplot2. Because with your code modified for ggplot2 v 0.9.3, I get this:
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(position = "stack", aes(x = Form, y = Percentage, ymax = Percentage, label = Percentage, hjust = 0.5))
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
You see that the text objects are normally placed properly. There are places where the bars are just too short so that the numbers overlap. You can also play with the size parameter.
To rectify that, you could do something like this to add up the numbers by yourself.
df <- ddply(df, .(Form, Sample_type, Sample_name), transform,
cum.perc = Reduce('+', list(Percentage/2,cumsum(c(0,head(Percentage,-1))))))
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(aes(x = Form, y = cum.perc, ymax = cum.perc, label = Percentage, hjust = 0.5), size=2.7)
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
This gives:
Here a solution using barchart from lattice.
library(latticeExtra)
barchart(Percentage~Form|Sample_type*Sample_name,data=dat,
groups =Position,stack=T,
panel=function(...){
panel.barchart(...)
ll <- list(...)
keep <- !is.na(ll$groups[ll$subscripts])
x <- as.numeric(ll$x[keep])
y <- as.numeric(ll$y[keep])
groups <- as.numeric(factor(ll$groups)[ll$subscripts[keep]])
for (i in unique(x)) {
ok <- x == i
ord <- sort.list(groups[ok])
pos <- y[ok][ord] > 0
nok <- sum(pos, na.rm = TRUE)
h <- y[ok][ord][pos]
panel.text(x = rep(i, nok),y = cumsum(h)-0.5*h,
label = h,cex=1.5)
}
},
auto.key = list(columns = 5),
par.settings = ggplot2like(n = 5),
lattice.options = ggplot2like.opts())

Resources