Add only one panel border line between facets in ggplot - r

For the following sample df
df = data.frame(x = c(2,3,4),y = c(4,5,6),group.a= c("1","1","2"),group.b = c("a","b","b"))
I want to just add a horizontal line in-between the y axis facet grids and after browsing different posts here I have tried using the panel.border = element_rect() argument however that gives me all four borders (top, right, bottom, left)
ggplot(df,aes(x=x,y=y)) + facet_grid(group.a~group.b) + theme_minimal() +
theme(legend.position = "bottom",
legend.title = element_blank(),
legend.direction = "horizontal",
legend.margin = margin(-20,0,0,0),
panel.grid = element_blank(),
panel.border = element_rect(color = "black", fill = NA, size = .5)
axis.text.x = element_blank(),
axis.line.y = element_line(size = .5),
axis.line.x = element_line(size = .5),
strip.placement = "outside")
Is there a way to just have the bottom and left border of the panel borders? Thanks!

There aren't any theme elements that fit the bill here; you would need custom annotations. Fortunately, annotation_custom applies to each panel, so this can be done with a couple of lines of code
library(ggplot2)
df = data.frame(x = c(2,3,4),y = c(4,5,6),
group.a= c("1","1","2"),group.b = c("a","b","b"))
ggplot(df,aes(x=x,y=y)) +
facet_grid(group.a~group.b) +
geom_point(col = "white") +
theme_minimal() +
annotation_custom(grid::linesGrob(y = c(0, 0), gp = grid::gpar(lwd = 3))) +
annotation_custom(grid::linesGrob(x = c(0, 0), gp = grid::gpar(lwd = 3))) +
theme(panel.grid = element_blank(),
strip.placement = "outside",
axis.text.x = element_blank())

Related

How to vertically align elements of legend box

I have below ggplot
library(ggplot2)
library(grid)
theme_set(theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position=c(0,1),
legend.justification = c(0,1),
legend.box.margin = margin(5, l = 5, unit = 'mm'),
legend.box = 'horizontal'
))
ggplot(diamonds,aes(x,y,color=z))+
geom_point()+
scale_colour_gradient2('Time [min]',
low='lightgray',
mid='red3',
high='red4',
midpoint=15)
With this I am getting below plot,
However I wanted to horizontally align the colour definition in the legend, while colour title (i.e. Time [min]) should be on top of the colour definition. Is there any way to achieve this
By adding legend.direction = 'horizontal' and some guides,
ggplot(diamonds,aes(x,y,color=z))+
geom_point()+
scale_colour_gradient2('Time [min]',
low='lightgray',
mid='red3',
high='red4',
midpoint=15) +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position=c(0,1),
legend.justification = c(0,1),
legend.box.margin = margin(5, l = 5, unit = 'mm'),
legend.box = 'horizontal',
legend.direction = 'horizontal'
) +
guides(colour = guide_colourbar(title.position="top", title.hjust = 0.5),
size = guide_legend(title.position="top", title.hjust = 0.5))

Removing grid between transparent ggplot plots arranged by ggarrange

I'm trying to produce a figure containing multiple ggplot2 plots arranged by ggarrange from the package ggpubr and annotated on the left side. The ggplot2 plots are transparent or have a transparent background.
The issue arose lately (i.e. I did not confront it this year earlier) where a light grey line appears between the plots and the annotation text on the left side as shown in the image below. And it is more prominent when the figure is inserted in LaTeX.
I tried to play with the individual plots, but there is no plot.border only panel.border, thus, all my trials were not successful!
My maschine information:
R 3.6.3 on Ubuntu 20.04.2 LTS
ggplot2 3.3.5
ggpubr 0.4.0
The code I used to produce it (and was inspired by this):
library(ggplot2)
library(ggpubr)
# Box plot (bp)
bxp <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco")+
theme_bw(base_size = 8)+
theme(legend.position = "bottom",
legend.title = element_blank(),
legend.text = element_text(size = 10),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "black",fill=NA,
size=0.1, linetype="solid"),
legend.key.width = unit(5, "mm"),
legend.spacing = unit(1, 'mm'),
legend.key.size = unit(0.5, "mm"),
legend.margin = margin(3,1,3,1, unit = "mm"))+
theme(panel.grid.major =element_line(colour = "black",linetype = "dotted",size = 0.05),
panel.grid.minor = element_blank(),
plot.margin = margin( 2.25,4.5,2.25,1, unit = "mm"),
plot.title = element_text(margin = margin(1,0,1,0, unit = "mm"),size = 10),
axis.line = element_blank(),
axis.text = element_text(colour = "black"), axis.title= element_blank(),
panel.border = element_rect(colour = "black", fill = NA, size=0.75),
panel.background = element_rect(color = NA),
rect = element_rect(fill = "transparent") )+ # all rectangles
labs(title = expression("(a)"))+
theme(axis.text = element_text(colour = "black"))
# Dot plot (dp)
dp <- ggdotplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco", binwidth = 1)+
theme_bw(base_size = 8)+
theme(legend.position = "bottom",
legend.title = element_blank(),
legend.text = element_text(size = 10),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "black",fill=NA,
size=0.1, linetype="solid"),
legend.key.width = unit(5, "mm"),
legend.spacing = unit(1, 'mm'),
legend.key.size = unit(0.5, "mm"),
legend.margin = margin(3,1,3,1, unit = "mm"))+
theme(panel.grid.major =element_line(colour = "black",linetype = "dotted",size = 0.05),
panel.grid.minor = element_blank(),
plot.margin = margin( 2.25,4.5,2.25,1, unit = "mm"),
plot.title = element_text(margin = margin(1,0,1,0, unit = "mm"),size = 10),
axis.line = element_blank(),
axis.text = element_text(colour = "black"), axis.title= element_blank(),
panel.border = element_rect(colour = "black", fill = NA, size=0.75),
panel.background = element_rect(color = NA),
rect = element_rect(fill = "transparent") )+ # all rectangles
labs(title = expression("(b)"))+
theme(axis.text = element_text(colour = "black"))
bxp1<-bxp+labs(title = expression("(c)"))
dp1<-dp+labs(title = expression("(d)"))
figure <- ggarrange(bxp,bxp1,dp,dp1,
ncol = 2, nrow = 2,align = c("hv"))
figure <-annotate_figure(figure,left = text_grob("left side ",
color = "black",size = 10, rot = 90))
ggsave(plot = figure,
filename = paste0("question.png"),
height = 180, width =180, units = "mm", dpi = 300, device = "png",limitsize = FALSE)
Edit:
I can forget about the transparency by removeing rect = element_rect(fill = "transparent") ,however, the light grey gridline appears between the arragned plots and the antonatioed text of the left side.
The question can be: How to change the background of textgrob() to white instaed of transparent?
The issue with transparent arranged plots still exists. However, a progressive solution can be:
Producing ggplot2 plots with a white background by removing rect = element_rect(fill = "transparent") .
Using another approach to annotate and arrange plots:
library(gridExtra)
library(grid)
library(gridtext)
yleft <- textGrob("left side",
rot = 90, gp = gpar(fontsize = 10, fill= "white",color="black"))
figure <- grid.arrange(bxp,bxp1,
dp,dp1,
ncol = 2, nrow = 2,
left=yleft)
Update (March 2022):
using the approach in the question and changing the background bg to white.
ggsave(plot = figure,
filename = paste0("question.png"),
height = 180, width =180, units = "mm", dpi = 300,
device = "png",limitsize = FALSE,bg="white")

How to draw an empty ggplot with just the legend?

My question is very similar to this question, but it's not the same.
I am looking for a way to create an empty ggplot with just the legend. However, in contrast to the autohor of the question I linked at the top, I actually need to create just the legend with no plot area included in the image.
I tried the following code:
ggplot(NULL, aes(color = ""))+
geom_blank()+
scale_color_manual(values = "black", labels = "Something")+
guides(color = guide_legend())+
theme(legend.box.background = element_rect(color = "black"))
But I'm getting the opposite of what I want - I am getting an empty plot area with no legend, like this:
And I would like my end result to look like this (I drew this in Paint):
Any help would be appreciated!
You can make a normal plot, then play with theme to achieve the desired result.
library(ggplot2)
ggplot(data.frame(x = 1, y = 1, colour = 'Something'), aes(x, y, fill = colour))+
geom_point(alpha=0, shape = 0)+ # completely transparent rectangular point
scale_fill_manual(values='black', drop=FALSE) +
guides(fill = guide_legend(override.aes = list(alpha=1, size = 40)))+ # showing the point in the legend
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.position = c(0.5, 0.5), # move the legend to the center
legend.title = element_blank(),
legend.text = element_text(size = 40),
legend.key = element_rect(fill='NA'),
panel.grid = element_blank(),
panel.border = element_rect(colour = "black", fill='white', size=1)
)
Get the legend how you want it to look, then extract it with cowplot::get_legend:
library(grid)
library(cowplot)
library(ggplot2)
grid.newpage()
grid.draw(get_legend(
ggplot(data.frame(x = 1, y = 1), aes(x, y, fill = "Something")) +
geom_col(size = 20)+
scale_fill_manual(values = "white", labels = "Something", name = "") +
theme_bw() +
theme(legend.box.background = element_rect(color = "black"),
legend.title = element_text(size = 30),
legend.key.size = unit(60, "points"),
legend.text = element_text(size = 24),
legend.key = element_rect(colour = "black"),
legend.box.margin = margin(20, 20, 20, 20))))

Removing ticks from scale_fill_gradientn colorbar

I've the following code I'm working with:
colVec = c(heat.colors(100), "#828282")
colVec = rev(colVec)
remove_axes <- theme(
axis.text = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
axis.title = element_blank()
)
maineMap <- me_base +
geom_polygon(data = graphData, aes(fill = infProp), color = "white") +
geom_polygon(color = "black", fill = NA) +
theme_bw() +
remove_axes
breakVec = seq(0,1,by=0.01)
labelVec = rep("",length(breakVec))
labelVec[1] = 0
labelVec[length(labelVec)] = 1
labelVec[floor(length(labelVec)/2)] = 0.5
countyMap <- maineMap +
scale_fill_gradientn(colours = colVec,
breaks = breakVec,
limits = c(0, 1),
labels = labelVec)
countyMap
Which produces the following image:
My question is how do I remove all the tick bars on the color bar, and only place them at the points 0, 0.5, and 1? Additionally, can I make the colorbar appear differently, such as thicker or in a different format?

Add legend to ggplot object (why two legends?)

I created a ggplot2 object:
a <- replicate(8,rnorm(100))
colnames(a) <- letters[1:8]
b < -melt(a,id.vars=1:1)
colnames(b) <- c("c","variable","value")
ggplot(b,aes(x = c,y = value, colour = variable, linetype = variable)) +
geom_line()+
geom_point(aes(shape = factor(variable)), size = 1.7) +
scale_x_continuous(limits = c(-1, 1),
breaks = seq(-1, 1, 0.1),
expand=c(0.01, 0.01)) +
scale_y_continuous(limits = c(-1, 1),
breaks = seq(-1, 1, 0.1),
expand = c(0.01, 0.01))+
theme_bw(base_size = 12, base_family = "Helvetica") +
theme(axis.text=element_text(size = 10),
axis.title=element_text(size = 10),
text = element_text(size = 10),
axis.line = element_line(size = 0.25),
axis.ticks=element_line(size = 0.25),
panel.grid.major = element_blank(),
#panel.grid.minor = element_blank(),
panel.border = element_rect(colour = "black", fill = NA, size = 0.5),
panel.background = element_blank(),
legend.position = "top" ,
legend.direction = "vertical",
legend.title = element_blank(),
legend.text = element_text(size = 13),
legend.background = element_blank(),
legend.key = element_blank()) +
labs(x = '', y = '', title = "") +
theme(plot.title = element_text(size=10)) +
theme(strip.text.x = element_text(size = 8,color="black"),
strip.background = element_blank()) +
theme(strip.text.x = element_text(size = 8, colour = "black"))
My problem is the following:
when I create the legend, there is a separate legend for the colors and a separate one for the points.
How can I create a single legend for each of the 8 variables?
Let me minimise your code and focus on the legend issue. This is what you have now.
ggplot(b,aes(x = c, y = value, colour = variable, linetype = variable)) +
geom_line() +
geom_point(aes(shape = factor(variable)),size=1.7)
Your data frame, b has variable as factor. You use this in two ways here; variable and factor(variable). You can simply use variable for shape in geom_point; make all variable identical.
ggplot(b,aes(x = c, y = value, colour = variable, linetype = variable)) +
geom_line()+
geom_point(aes(shape = variable),size = 1.7)
I saw some warning messages related to colours and other things. You may want to take care of them. But, for legend, this is one way to go.
Take from the ideas on this page: http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/#modifying-the-text-of-legend-titles-and-labels
I edited your code to make the data visible (you had problems with your x-axis limits. Note the final three lines. These commands tell ggplot to create only one legend.
a<-replicate(6,rnorm(100))
colnames(a)<-letters[1:6]
b<-melt(a,id.vars=1:1)
colnames(b)<-c("c","variable","value")
ggplot(b,aes(x=c,y=value,colour=variable,linetype=variable)) +
geom_line() + geom_point(aes(shape=factor(variable)),size=1.7)+
scale_x_continuous(limits=c(0,100))+
scale_y_continuous(limits=c(-2,2),breaks=seq(-2,2,0.1),expand=c(0.01,0.01))+
theme_bw(base_size=12, base_family="Helvetica") +
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10),
text = element_text(size=10),
axis.line = element_line(size=0.25),
axis.ticks=element_line(size=0.25),
panel.grid.major = element_blank(),
#panel.grid.minor = element_blank(),
panel.border = element_rect(colour="black",fill=NA,size=0.5),
panel.background = element_blank(),
legend.position="top" ,
legend.direction="vertical",
legend.title=element_blank(),
legend.text=element_text(size=13),
legend.background=element_blank(),
legend.key=element_blank())+
labs(x='', y='',title="")+
theme(plot.title=element_text(size=10))+
theme(strip.text.x = element_text(size = 8,color="black"),strip.background=element_blank())+
theme(strip.text.x = element_text(size = 8,color="black"))+
scale_colour_discrete(name ="Factor")+
scale_linetype_discrete(name ="Factor") +
scale_shape_discrete(name ="Factor")

Resources