Bring to front the panel grid - r

The panel grid of ggplot2 plots is created to be on the background of the plot. My question is: is it possibly modified to be brought over the plot?
I can partly see the solution in substituting the grid by geom_hline() or geom_vline() layers. However, that can be tricky with more complicated plots or while plotting maps, and thus my question is only concerning modifying the elements of theme().
library(tidyverse)
df <- data.frame(x = c(1,2),
y = c(1,2))
df %>% ggplot(aes(x, y)) +
geom_area() + theme(
panel.grid = element_line(color = "red")
)
A cheaty solution of substituting the grid by geom_hline() or geom_vline()
grd_x <- seq(1, 2, length.out = 9)
grd_y <- seq(0, 2, length.out = 9)
df %>% ggplot(aes(x, y)) +
geom_area() +
geom_hline(yintercept = grd_y, col = "red") +
geom_vline(xintercept = grd_x, col = "red")

As mentioned in 1 of the comments, you can use theme(panel.ontop = TRUE). However, when trying this, I couldn't see the graph anymore. Therefore you need to make sure the background image of the panel is blank when doing changing panel.ontop to TRUE:
library(tidyverse)
df <- data.frame(x = c(1,2),
y = c(1,2))
df %>% ggplot(aes(x, y)) +
geom_area() +
theme(panel.grid = element_line(color = "red"),
panel.ontop = TRUE, panel.background = element_rect(color = NA, fill = NA)
)

Related

ggplot2 - split one legend (two color scales) and delete another

I am having much trouble configuring plot legend in ggplot2. I have two data frames:
require(ggplot2)
mat <- rep(c("None", "wood", "steel"), each = 4)
feet = rep(seq(0,3), 3)
load = c(3:6, 4:7, 5:8)
soil <- data.frame(
feet = feet,
test = rep(1:3, each = 4),
load = c(0.1, 0.2, 0.3, 0.04,
0.5, 0.6, 0.7, 0.44,
0.8, 0.9, 1.0, 0.74)
)
dat <- rbind(
data.frame(
feet = feet,
mat = mat,
load = c(3:6, 4:7, 5:8),
SF = FALSE
),
data.frame(
feet = feet,
mat = mat,
load = c(6:9, 7:10, 8:11),
SF = TRUE
)
)
I would like a plot with a legend for dat$mat and a legend for soil$test:
myplot <- ggplot(dat, aes(x = load, y = feet)) +
geom_line(aes(color = mat, linetype = SF)) +
geom_path(dat = soil, aes(x = load, y = feet, color = factor(test)))
myplot
I don't want the legend named SF. Also, I would like to split the legend named mat into two legends, mat (values = "none", "wood", "steel") from the dat data.frame, and test (values = 1, 2, 3) from the soil data.frame.
I've tried theme(legend.position = "none"), and many other various combinations of code that would fill the page if I listed them all. Thanks for any assistance you can offer.
update - there is a much better option offered in this answer. I will leave this because hacking legends with a fake aesthetic might still be needed in certain cases.
As #M-M correctly said - ggplot doesn't want to draw two legends for one aesthetic.
I truly hope that you won't often need to do something like the following hack:
Make a fake aesthetic (I chose alpha), and define the color for each line manually.
Then change your legend keys using override.aes manually.
If you have more than this data to show, consider different ways of visualisation / data separation. A very good thing is facetting.
library(ggplot2)
library(dplyr)
ggplot(dat, aes(x = load, y = feet)) +
geom_line(aes(color = mat, linetype = SF)) +
geom_path(dat = filter(soil,test ==1),
aes(x = load, y = feet, alpha = factor(test)), color = 'red') +
geom_path(dat = filter(soil,test ==2),
aes(x = load, y = feet, alpha = factor(test)), color = 'brown') +
geom_path(dat = filter(soil,test ==3),
aes(x = load, y = feet, alpha = factor(test)), color = 'green') +
scale_alpha_manual(values = c(rep(1,3))) +
scale_linetype(guide = FALSE) +
guides( alpha = guide_legend(title = 'test',
override.aes = list(color = c('red','brown','green'))))
Or you can make two separate ggplots, then overlay one using cowplot:
library(cowplot) #cowplot_1.0.0
library(ggplot2)
myplot <- ggplot(dat, aes(x = load, y = feet)) +
geom_line(aes(color = mat, linetype = SF)) +
scale_linetype(guide = FALSE) +
lims(x = c(0,11), y = c(0,3)) +
theme(legend.justification = c(0, 1), # move the bottom legend up a bit
axis.text.x = element_blank(), # remove all the labels from the base plot
axis.text.y = element_blank(),
axis.title = element_blank())
myplot2 <- ggplot() +
geom_path(dat = soil, aes(x = load, y = feet, color = factor(test))) +
theme_half_open() +
lims(x = c(0,11), y = c(0,3))
aligned_plots <- align_plots(myplot, myplot2, align="hv", axis="tblr")
ggdraw(aligned_plots[[1]]) + draw_plot(aligned_plots[[2]])
Actually, there is a better option than my previous hack - I am sure this must have been around back then, but I was simply not aware of it. Adding a new scale is very easy with ggnewscale.
ggnewscale is currently to my knowledge the only package on CRAN that allows several (discrete!) scales for the same aesthetic. For continuous scales, there is now also ggh4x::scale_color/fill_multi. And there is also Claus Wilke's relayer package on GitHub.
I really like the ggnewscale package because it's super easy to use and works with literally all aesthetics.
ggplot(mapping = aes(x = load, y = feet)) +
geom_line(data = dat, aes(color = mat, linetype = SF)) +
scale_linetype(guide = FALSE) + # This is to delete the linetype legend
ggnewscale::new_scale_color() +
geom_path(data = soil, aes(x = load, y = feet, color = as.factor(test))) +
scale_color_manual("Test", values = c('red','brown','green'))

Join lines across multiple plots R geological cross section

I am trying to recreate a geological cross section similar to the one below, which show various rock parameters (x axis) plotted against depth (y axis)
I can nicely recreate the individual plots in ggplot2 and grid together to create something very similar. To finish off i would really like to join lines between the plots which show regions of similar geology as in the picture.
Below is some code which plots the charts with the horizontal lines, what i would really to do is to join lines ( if possible in R) and if possible align the charts based on the line
library(ggplot2)
library(gridExtra)
df1 = data.frame(replicate(2,sample(0:200,100,rep=TRUE)))
df1$depth = seq.int(nrow(df1))
df2 = data.frame(replicate(2,sample(0:200,100,rep=TRUE)))
df2$depth = seq.int(nrow(df1))
top1 = 32
top2 = 50
plot1 = ggplot(df1, aes(y = depth, x = X1))+
scale_y_continuous(trans = "reverse")+
geom_path()+
geom_hline(yintercept=top1, colour = "red")+
annotate(geom="text", x=25, y=top1, label=top1, color="red")+
theme_bw()+
theme(panel.grid.major = element_line(colour = "grey"), panel.background = element_rect(colour = "black", size=0.5))+
ylab("Depth ft")+
ggtitle("plot1")
plot2 = ggplot(df2, aes(y = depth, x = X1))+
scale_y_continuous(trans = "reverse")+
geom_path()+
geom_hline(yintercept=top2, colour = "red")+
annotate(geom="text", x=25, y=top2, label=top2, color="red")+
theme_bw()+
theme(panel.grid.major = element_line(colour = "grey"), panel.background = element_rect(colour = "black", size=0.5))+
ylab("Depth ft")+
ggtitle("plot2")
grid.arrange (plot1, plot2, ncol=2)
This would be the desired result i would be looking for with the lines joined and if possible aligned.
Thanks for any help or advice given
Cheers
I can't help with the line-joining part, but the idea of the shifted scales sounded pretty interesting. This solution takes an arbitrary number of dataframes and an accompanying list of isolines, then shifts the y-scale so that each isoline is at 0.
Each dataframe is then plotted and the y-axes are renumbered appropriately.
library(purrr)
library(dplyr)
library(ggplot2)
# library(cowplot)
# I never load `cowplot` because it changes some settings onload.
# I just call the namespace with `cowplot::plot_grid(...)`
# You will need it installed though.
depth_plots <- function(..., isolines) {
dats <- list(...)
stopifnot(length(dats) == length(isolines))
scaled_dats <- map2(dats, isolines, ~.x %>% mutate(sc_depth = depth - .y))
new_range <-
map(scaled_dats, ~range(.x$sc_depth)) %>%
unlist() %>%
range() %>%
scales::expand_range(mul = 0.05)
plots <- map2(
scaled_dats, isolines,
~ggplot(.x, aes(y = sc_depth, x = X1)) +
scale_y_continuous(
trans = "reverse",
breaks = scales::extended_breaks()(.x$depth) - .y,
labels = scales::extended_breaks()(.x$depth)
) +
geom_path() +
geom_hline(yintercept=0, colour = "red") +
annotate(geom="text", x=25, y=0, label=.y, color="red") +
coord_cartesian(
ylim = new_range
) +
theme_bw()
)
cowplot::plot_grid(plotlist = plots, nrow = 1)
}
To test out the varying depth structures, I changed your sample data a bit:
df1 = data.frame(replicate(2,sample(0:200,100,rep=TRUE)))
df1$depth = seq.int(nrow(df1))
df2 = data.frame(replicate(2,sample(0:200,100,rep=TRUE)))
df2$depth = seq.int(nrow(df1))*0.75
df3 = data.frame(replicate(2,sample(0:200,100,rep=TRUE)))
df3$depth = seq.int(nrow(df1))*2
depth_plots(df1, df2, df3, isolines = c(32,50, 4))
Hope that gets you started!

Alignment of y axis labels in faced_grid and ggplot?

By using ggplot and faced_grid functions I'm trying to make a heatmap. I have a categorical y axis, and I want y axis labels to be left aligned. When I use theme(axis.text.y.left = element_text(hjust = 0)), each panels' labels are aligned independently. Here is the code:
#data
set.seed(1)
gruplar <- NA
for(i in 1:20) gruplar[i] <- paste(LETTERS[sample(c(1:20),sample(c(1:20),1),replace = T) ],
sep="",collapse = "")
gruplar <- cbind(gruplar,anagruplar=rep(1:4,each=5))
tarih <- data.frame(yil= rep(2014:2019,each=12) ,ay =rep_len(1:12, length.out = 72))
gruplar <- gruplar[rep(1:nrow(gruplar),each=nrow(tarih)),]
tarih <- tarih[rep_len(1:nrow(tarih),length.out = nrow(gruplar)),]
grouped <- cbind(tarih,gruplar)
grouped$value <- rnorm(nrow(grouped))
#plot
p <- ggplot(grouped,aes(ay,gruplar,fill=value))
p <- p + facet_grid(anagruplar~yil,scales = "free",
space = "free",switch = "y")
p <- p + theme_minimal(base_size = 14) +labs(x="",y="") +
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 90))
p <- p + geom_raster(aes(fill = value), na.rm = T)
p + theme(axis.text.y.left = element_text(hjust = 0, size=14))
I know that by putting spaces and using a mono-space font I can solve the problem, but I have to use the font 'Calibri Light'.
Digging into grobs isn't my favourite hack, but it can serve its purpose here:
# generate plot
# (I used a smaller base_size because my computer screen is small)
p <- ggplot(grouped,aes(ay,gruplar,fill=value)) +
geom_raster(aes(fill = value),na.rm = T) +
facet_grid(anagruplar~yil,scales = "free",space = "free",switch = "y") +
labs(x="", y="") +
theme_minimal(base_size = 10) +
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 90),
axis.text.y.left = element_text(hjust = 0, size=10))
# examine ggplot object: alignment is off
p
# convert to grob object: alignment is unchanged (i.e. still off)
gp <- ggplotGrob(p)
dev.off(); grid::grid.draw(gp)
# change viewport parameters for left axis grobs
for(i in which(grepl("axis-l", gp$layout$name))){
gp$grobs[[i]]$vp$x <- unit(0, "npc") # originally 1npc
gp$grobs[[i]]$vp$valid.just <- c(0, 0.5) # originally c(1, 0.5)
}
# re-examine grob object: alignment has been corrected
dev.off(); grid::grid.draw(gp)
I guess one option is to draw the labels on the right-hand side, and move that column in the gtable,
p <-ggplot(grouped,aes(ay,gruplar,fill=value)) +
facet_grid(anagruplar~yil,scales = "free",space = "free",switch = "y") +
geom_raster(aes(fill = value),na.rm = T) +
theme_minimal(base_size = 12) + labs(x="",y="") +
scale_y_discrete(position='right') +
theme(strip.placement = "outside", strip.text.y = element_text(angle = 90))+
theme(axis.text.y.left = element_text(hjust = 0,size=14))
g <- ggplotGrob(p)
id1 <- unique(g$layout[grepl("axis-l", g$layout$name),"l"])
id2 <- unique(g$layout[grepl("axis-r", g$layout$name),"l"])
g2 <- gridExtra::gtable_cbind(g[,seq(1,id1-1)],g[,id2], g[,seq(id1+1, id2-1)], g[,seq(id2+1, ncol(g))])
library(grid)
grid.newpage()
grid.draw(g2)
This seems like a bug in ggplot2, or at least what I consider an undesirable / unexpected behavior. You may have seen the approach suggested here, which uses string padding on a mono-space font to achieve the alignment.
This is pretty hacky, but if you need to achieve alignment using a particular font, you might replace the axis labels altogether with geom_text. I have a mostly-working solution, but it is ugly, in that each step seems to break something else!
library(ggplot2); library(dplyr)
# To add a blank facet before 2014, I convert to character
grouped$yil = as.character(grouped$yil)
# I add some rows for the dummy facet, in year "", to use for labels
grouped <- grouped %>%
bind_rows(grouped %>%
group_by(gruplar) %>%
slice(1) %>%
mutate(yil = "",
value = NA_real_) %>%
ungroup())
p <- ggplot(grouped,
aes(ay,gruplar,fill=value)) +
geom_raster(aes(fill = value),na.rm = T) +
scale_x_continuous(breaks = 4*0:3) +
facet_grid(anagruplar~yil,
scales = "free",space = "free",switch = "y") +
theme_minimal(base_size = 14) +
labs(x="",y="") +
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 90),
axis.text.y.left = element_blank(),
panel.grid = element_blank()) +
geom_text(data = grouped %>%
filter(yil == ""),
aes(x = -40, y = gruplar, label = gruplar), hjust = 0) +
scale_fill_continuous(na.value = "white")
p
(The last problem with this plot that I can see is that it shows an orphaned "0" on the x axis of the dummy facet. Need another hack to get rid of that!)

How to choose the right parameters for dotplot in r ggplot

I intend to make a dot plot somewhat like this:
But there's some issue with the code:
df = data.frame(x=runif(100))
df %>%
ggplot(aes(x )) +
geom_dotplot(binwidth =0.01, aes(fill = ..count..), stackdir = "centerwhole",dotsize=2, stackgroups = T, binpositions = "all")
how to choose bin width to avoid dots overlapping, bins wrapping itself in 2 columns or dots get truncated at the top and bottom?
And why is the y axis showing decimal points instead of count? And how to color the dots by x value? I tried fill = x and no color is shown.
The overlap is caused by the dotsize > 1; as #Jimbuo said, the decimal values on the y axis is due to the internals of this geom; for the fill and color you can use the ..x.. computed variable:
Computed variables
x center of each bin, if binaxis is "x"
df = data.frame(x=runif(1000))
library(dplyr)
library(ggplot2)
df %>%
ggplot(aes(x, fill = ..x.., color = ..x..)) +
geom_dotplot(method = 'histodot',
binwidth = 0.01,
stackdir = "down",
stackgroups = T,
binpositions = "all") +
scale_fill_gradientn('', colours = c('#5185FB', '#9BCFFD', '#DFDFDF', '#FF0000'), labels = c(0, 1), breaks = c(0,1), guide = guide_legend('')) +
scale_color_gradientn(colours = c('#5185FB', '#9BCFFD', '#DFDFDF', '#FF0000'), labels = c(0, 1), breaks = c(0,1), guide = guide_legend('')) +
scale_y_continuous() +
scale_x_continuous('', position = 'top') +
# coord_equal(ratio = .25) +
theme_classic() +
theme(axis.line = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
aspect.ratio = .25,
legend.position = 'bottom',
legend.direction = 'vertical'
)
Created on 2018-05-18 by the reprex package (v0.2.0).
First from the help of ?geom_dotplot
When binning along the x axis and stacking along the y axis, the
numbers on y axis are not meaningful, due to technical limitations of
ggplot2. You can hide the y axis, as in one of the examples, or
manually scale it to match the number of dots.
Thus you can try following. Note, the coloring is not completly fitting the x axis.
library(tidyverse)
df %>%
ggplot(aes(x)) +
geom_dotplot(stackdir = "down",dotsize=0.8,
fill = colorRampPalette(c("blue", "white", "red"))(100)) +
scale_y_continuous(labels = c(0,10), breaks = c(0,-0.4)) +
scale_x_continuous(position = "top") +
theme_classic()
For the correct coloring, you have to calculate the bins by yourself using e.g. .bincode:
df %>%
mutate(gr=with(.,.bincode(x ,breaks = seq(0,1,1/30)))) %>%
mutate(gr2=factor(gr,levels = 1:30, labels = colorRampPalette(c("blue", "white", "red"))(30))) %>%
arrange(x) %>%
{ggplot(data=.,aes(x)) +
geom_dotplot(stackdir = "down",dotsize=0.8,
fill = .$gr2) +
scale_y_continuous(labels = c(0,10), breaks = c(0,-0.4)) +
scale_x_continuous(position = "top") +
theme_classic()}

adding a border around a grob (R) [duplicate]

I'm using the code below:
# Libs
require(ggplot2); require(gridExtra); require(grid)
# Generate separate charts
chrts_list_scts <- list()
# Data
data("mtcars")
# A
chrts_list_scts$a <- ggplot(mtcars) +
geom_point(size = 2, aes(x = mpg, y = disp,
colour = as.factor(cyl))) +
geom_smooth(aes(x = mpg, y = disp),
method = "auto") +
xlab("MPG") +
ylab("Disp") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "none")
# B
chrts_list_scts$b <- ggplot(mtcars) +
geom_point(size = 2, aes(x = mpg, y = drat,
colour = as.factor(cyl))) +
geom_smooth(aes(x = mpg, y = drat),
method = "auto") +
xlab("MPG") +
ylab("Drat") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "none")
# C
chrts_list_scts$c <- ggplot(mtcars) +
geom_point(size = 2, aes(x = mpg, y = qsec,
colour = as.factor(cyl))) +
geom_smooth(aes(x = mpg, y = qsec),
method = "auto") +
xlab("MPG") +
ylab("QSEC") +
guides(colour = guide_legend(title = "cyl")) +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "bottom",
legend.key = element_rect(colour = NA))
# Arrange grid
png(filename = "chrts.PNG", width = 6,
height = 10, units = 'in', res = 300)
title_text <- c("mtcars")
chrts_list_scts$all_scts <- grid.arrange(chrts_list_scts$a,
chrts_list_scts$b,
chrts_list_scts$c,
top =
textGrob(label = title_text,
gp = gpar(
fontsize = 14,
font = 2)))
dev.off()
rm(title_text)
To generate the following chart:
I'm interested in adding border around that chart, as in the picture below:
Attempts
I tried to address this request via adding polygonGrob in the code:
chrts_list_scts$all_scts <- grid.arrange(chrts_list_scts$dep_work,
chrts_list_scts$chld_work,
chrts_list_scts$pens,
polygonGrob(x = c(0,0.5,1.05),
y = c(0,0.5,1.05)
),
top =
textGrob(label = title_text,
gp = gpar(
fontsize = 14,
font = 2)))
but this generates a pointless chart with one line across in the bottom. I had a look at the seeming similar discussion on SO but it wasn't clear to me how to arrive at a working solution.
Side requirements
In addition to generating the border, I would like to:
Be able to exercise some control over the border aesthetics, like changing size and colour of the border.
Ideally, I would like to encapsulate this solution within the arrange.grid call. So at the object chrts_list_scts$all_scts has all elements including charts and neat border around all of them.
I will be happy to accept solutions that address the major requirements with respect to the border only, if there is a suggested solution that matches the remaining two points it will be even nicer.
1) Using the iris example (but further simplified) from the link provided in the question just add the last line. Modify the gpar(...) components (and possibly the width and height) to get different aesthetics. (This is not encapsulated in the grid.arrange call.)
library(ggplot2)
library(grid)
library(gridExtra)
g <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point()
grid.arrange(g, g, ncol=2)
# next line adds border
grid.rect(width = .98, height = .98, gp = gpar(lwd = 2, col = "blue", fill = NA))
(continued after plot)
2) This is a variation of solution (1) in which on the plus side encapsulates both the graphics and border in the gt gTree by creating grobs to hold each. On the other hand it does involve some additional complexity:
grid.newpage()
ga <- arrangeGrob(g, g, ncol = 2)
gb <- rectGrob(height = .98, width = .98, gp = gpar(lwd = 2, col = "blue", fill = NA)) # border, no fill
gt <- gTree(children = gList(ga, gb))
grid.draw(gt)
you can add a rectGrob to the gtable
grid.draw(gtable::gtable_add_grob(arrangeGrob(g, g, ncol=2),
rectGrob(gp=gpar(lwd=5, fill=NA)), 1, 1, 1, 2))
NOTE: fill=NA or fill='transparent' is required otherwise the rectangle can mask the objects below it.

Resources