Position ggplot text in each corner with facet - r

I have a data frame with 10 values in each of the 5 kinds and have 2 types.
df <- data.frame(x2=rnorm(100),y2=rnorm(100), type = c(rep("type a", 50), rep("type b", 50)), kind = rep(LETTERS[1:5],10))
I want to print the labels of percent of values in each quadrants. My current code is:
ggplot(df, aes(x2, y2)) + geom_point() +
geom_vline(xintercept = 0) +
geom_hline(yintercept = 0) +
geom_text(data = df, aes(x2, y2, label = "")) +
facet_grid(type~kind)
Current output:
Expected output (for example I showed percentage of kind A and B of type a, i want to plot percent values for all kinds and types):
Any suggestion would be great. Thanks!

You probably need to calculate the proportions outside ggplot2,
library(dplyr)
numbers <- df %>% group_by(type,kind) %>% mutate(cases = n()) %>%
add_count(x2>0,y2>0) %>% mutate(label=paste(round(n/cases*100),"%"),
x = ifelse(`x2 > 0`, Inf, -Inf),
y = ifelse(`y2 > 0`, Inf, -Inf),
hjust = ifelse(`x2 > 0`, 1, 0),
vjust = ifelse(`y2 > 0`, 1, 0))
ggplot(df, aes(x2, y2)) + geom_point() +
geom_vline(xintercept = 0) +
geom_hline(yintercept = 0) +
facet_grid(type~kind) +
geom_label(data=numbers, aes(label = label, x=x, y=y, vjust=vjust, hjust = hjust))

Related

Plot labels at ends of lines in stacked area chart

I have the following code
library(ggplot2)
library(dplyr)
# create data
time <- as.numeric(rep(seq(1,7),each=7)) # x Axis
value <- runif(49, 10, 100) # y Axis
group <- rep(LETTERS[1:7],times=7) # group, one shape per group
data <- data.frame(time, value, group)
# stacked area chart
ggplot(data, aes(x=time, y=value, fill=group)) +
geom_area()+
geom_text(data = data %>% filter(time == last(time)), aes(label = group,
x = time + 0.5,
y = value,
color = group)) +
guides(color = FALSE) + theme_bw() +
scale_x_continuous(breaks = scales::pretty_breaks(10))
Where i get
But i am aiming for link
Is there any solution for stacked area plot?
The question code is plotting the text labels in the value's of the last time, when in fact the areas are cumulative. And in reverse order.
Also, the following graph plots data created with the same code but with
set.seed(1234)
Then the data creation code is the same as in the question.
# stacked area chart
ggplot(data, aes(x=time, y=value, fill=group)) +
geom_area()+
geom_text(data = data %>%
filter(time == last(time)) %>%
mutate(value = cumsum(rev(value))),
aes(label = rev(group),
x = time + 0.5,
y = value,
color = rev(group))) +
guides(color = FALSE) + theme_bw() +
scale_x_continuous(breaks = scales::pretty_breaks(10))
Edit.
Following the discussion in the comments to this answer, I have decided to post code based on the comment by user Jake Kaupp.
ggplot(data, aes(x = time, y = value, fill = group)) +
geom_area()+
geom_text(data = data %>% filter(time == last(time)),
aes(x = time + 0.5, y = value,
label = rev(group), color = rev(group)),
position = position_stack(vjust = 0.5)) +
guides(color = FALSE) +
theme_bw() +
scale_x_continuous(breaks = scales::pretty_breaks(10))
You can use the text function to put text wherever you want. For example:
text(7.2, 350, "B", col="brown")
Here we go
time <- as.numeric(rep(seq(1,7),each=8)) # x Axis
value <- runif(56, 10, 100) # y Axis
group <- rep(LETTERS[1:8],times=7) # group, one shape per group
data <- data.frame(time, value, group)
round_df <- function(x, digits) {
# round all numeric variables
# x: data frame
# digits: number of digits to round
numeric_columns <- sapply(x, mode) == 'numeric'
x[numeric_columns] <- round(x[numeric_columns], digits)
x
}
data$value<- round_df(data$value, 2)
# stacked area chart
ggplot(data, aes(x=time, y=value, fill=group)) +
geom_area()+
geom_text(aes(x = time + 0.5, y = value, label=ifelse(time == max(time), group, NA)),position = position_stack(vjust = 0.5),check_overlap = TRUE)+
guides(color = FALSE) + theme_bw()+
scale_x_continuous(breaks = scales::pretty_breaks(10)) +
geom_text(aes(label=ifelse(time != min(time) & time != max(time),value, NA)),position = position_stack(vjust = 0.5),check_overlap = TRUE)+
geom_text(aes(x = time + 0.18,label=ifelse(time == min(time),value, NA)),position = position_stack(vjust = 0.5),check_overlap = TRUE)+
geom_text(aes(x = time - 0.18,label=ifelse(time == max(time),value, NA)),position = position_stack(vjust = 0.5),check_overlap = TRUE)
And get
Factor levels but why not letters? That is the next step :)
UPDATED
just converted factor to char data$group <- as.character(data$group)

ggplot2 add sum to chart

Using mtcars as an example, I've produced some violin plots. I wanted to add two things to this chart:
for each group, list n
for each group, sum a third variable (e.g. wt)
I can do (1) with the geom_text code below although (n) is actually plotted on the x axis rather than off to the side.
But I can't work out how to do (2).
Any help much appreciated!
library(ggplot2)
library(gridExtra)
library(ggthemes)
result <- mtcars
ggplot(result, aes(x = gear, y = drat, , group=gear)) +
theme_tufte(base_size = 15) + theme(line=element_blank()) +
geom_violin(fill = "white") +
geom_boxplot(fill = "black", alpha = 0.3, width = 0.1) +
ylab("drat") +
xlab("gear") +
coord_flip()+
geom_text(stat = "count", aes(label = ..count.., y = ..count..))
You can add both of these annotations by creating them in your dataframe temporarily prior to graphing. Using the dplyr package, you can create two new columns, one with the count for each group, and one with the sum of wt for each group. This can then be piped directly into your ggplot using %>% (alternatively, you could save the new dataset and insert it into ggplot the way you have it). Then with some minor edits to your geom_text call and adding a second one, we can create the plot you want. The code looks like this:
library(ggplot2)
library(gridExtra)
library(ggthemes)
library(magrittr)
library(dplyr)
result <- mtcars
result %>%
group_by(gear) %>%
mutate(count = n(), sum_wt = sum(wt)) %>%
ggplot(aes(x = gear, y = drat, , group=gear)) +
theme_tufte(base_size = 15) + theme(line=element_blank()) +
geom_violin(fill = "white") +
geom_boxplot(fill = "black", alpha = 0.3, width = 0.1) +
ylab("drat") +
xlab("gear") +
coord_flip()+
geom_text(aes(label = paste0("n = ", count),
x = (gear + 0.25),
y = 4.75)) +
geom_text(aes(label = paste0("sum wt = ", sum_wt),
x = (gear - 0.25),
y = 4.75))
The new graph looks like this:
Alternatively, if you create a summary data frame named result_sum, then you can manually add that into the geom_text calls.
result <- mtcars %>%
mutate(gear = factor(as.character(gear)))
result_sum <- result %>%
group_by(gear) %>%
summarise(count = n(), sum_wt = sum(wt))
ggplot(result, aes(x = gear, y = drat, , group=gear)) +
theme_tufte(base_size = 15) +
theme(line=element_blank()) +
geom_violin(fill = "white") +
geom_boxplot(fill = "black", alpha = 0.3, width = 0.1) +
ylab("drat") +
xlab("gear") +
coord_flip()+
geom_text(data = result_sum, aes(label = paste0("n = ", count),
x = (as.numeric(gear) + 0.25),
y = 4.75)) +
geom_text(data = result_sum, aes(label = paste0("sum wt = ", sum_wt),
x = (as.numeric(gear) - 0.25),
y = 4.75))
This gives you this:
The benefit to this second method is that the text isn't bold like in the first graph. The bold effect occurs in the first graph due to the text being printed over itself for all observations in the dataframe.
Thanks to those who helped.... I used this in the end which plots the calculated values, one set of classes being text based so using vjust to position the vertical offset.
thanks again!
library(ggplot2)
library(gridExtra)
library(ggthemes)
results <- mtcars
results$gear <- as.factor(as.character(results$gear)) #Turn 'gear' to text to simulate classes, then factorise
result_sum <- results %>%
group_by(gear) %>%
summarise(count = n(), sum_wt = sum(wt))
ggplot(results, aes(x = gear, y = drat, group=gear)) +
theme_tufte(base_size = 15) + theme(line=element_blank()) +
geom_violin(fill = "white") +
geom_boxplot(fill = "black", alpha = 0.3, width = 0.1) +
ylab("drat") +
xlab("gear") +
coord_flip()+
geom_text(data = result_sum, aes(label = paste0("n = ", count), x = (gear), vjust= 0, y = 5.25)) +
geom_text(data = result_sum, aes(label = paste0("sum wt = ", round(sum_wt,0)), x = (gear), vjust= -2, y = 5.25))

Showing median value in grouped boxplot in R

I have created boxplots using ggplot2 with this code.
plotgraph <- function(x, y, colour, min, max)
{
plot1 <- ggplot(dims, aes(x = x, y = y, fill = Region)) +
geom_boxplot()
#plot1 <- plot1 + scale_x_discrete(name = "Blog Type")
plot1 <- plot1 + labs(color='Region') + geom_hline(yintercept = 0, alpha = 0.4)
plot1 <- plot1 + scale_y_continuous(breaks=c(seq(min,max,5)), limits = c(min, max))
plot1 <- plot1 + labs(x="Blog Type", y="Dimension Score") + scale_fill_grey(start = 0.3, end = 0.7) + theme_grey()
plot1 <- plot1 + theme(legend.justification = c(1, 1), legend.position = c(1, 1))
return(plot1)
}
plot1 <- plotgraph (Blog, Dim1, Region, -30, 25)
A part of data I use is reproduced here.
Blog,Region,Dim1,Dim2,Dim3,Dim4
BlogsInd.,PK,-4.75,13.47,8.47,-1.29
BlogsInd.,PK,-5.69,6.08,1.51,-1.65
BlogsInd.,PK,-0.27,6.09,0.03,1.65
BlogsInd.,PK,-2.76,7.35,5.62,3.13
BlogsInd.,PK,-8.24,12.75,3.71,3.78
BlogsInd.,PK,-12.51,9.95,2.01,0.21
BlogsInd.,PK,-1.28,7.46,7.56,2.16
BlogsInd.,PK,0.95,13.63,3.01,3.35
BlogsNews,PK,-5.96,12.3,6.5,1.49
BlogsNews,PK,-8.81,7.47,4.76,1.98
BlogsNews,PK,-8.46,8.24,-1.07,5.09
BlogsNews,PK,-6.15,0.9,-3.09,4.94
BlogsNews,PK,-13.98,10.6,4.75,1.26
BlogsNews,PK,-16.43,14.49,4.08,9.91
BlogsNews,PK,-4.09,9.88,-2.79,5.58
BlogsNews,PK,-11.06,16.21,4.27,8.66
BlogsNews,PK,-9.04,6.63,-0.18,5.95
BlogsNews,PK,-8.56,7.7,0.71,4.69
BlogsNews,PK,-8.13,7.26,-1.13,0.26
BlogsNews,PK,-14.46,-1.34,-1.17,14.57
BlogsNews,PK,-4.21,2.18,3.79,1.26
BlogsNews,PK,-4.96,-2.99,3.39,2.47
BlogsNews,PK,-5.48,0.65,5.31,6.08
BlogsNews,PK,-4.53,-2.95,-7.79,-0.81
BlogsNews,PK,6.31,-9.89,-5.78,-5.13
BlogsTech,PK,-11.16,8.72,-5.53,8.86
BlogsTech,PK,-1.27,5.56,-3.92,-2.72
BlogsTech,PK,-11.49,0.26,-1.48,7.09
BlogsTech,PK,-0.9,-1.2,-2.03,-7.02
BlogsTech,PK,-12.27,-0.07,5.04,8.8
BlogsTech,PK,6.85,1.27,-11.95,-10.79
BlogsTech,PK,-5.21,-0.89,-6,-2.4
BlogsTech,PK,-1.06,-4.8,-8.62,-2.42
BlogsTech,PK,-2.6,-4.58,-2.07,-3.25
BlogsTech,PK,-0.95,2,-2.2,-3.46
BlogsTech,PK,-0.82,7.94,-4.95,-5.63
BlogsTech,PK,-7.65,-5.59,-3.28,-0.54
BlogsTech,PK,0.64,-1.65,-2.36,-2.68
BlogsTech,PK,-2.25,-3,-3.92,-4.87
BlogsTech,PK,-1.58,-1.42,-0.38,-5.15
Columns,PK,-5.73,3.26,0.81,-0.55
Columns,PK,0.37,-0.37,-0.28,-1.56
Columns,PK,-5.46,-4.28,2.61,1.29
Columns,PK,-3.48,2.38,12.87,3.73
Columns,PK,0.88,-2.24,-1.74,3.65
Columns,PK,-2.11,4.51,8.95,2.47
Columns,PK,-10.13,10.73,9.47,-0.47
Columns,PK,-2.08,1.04,0.11,0.6
Columns,PK,-4.33,5.65,2,-0.77
Columns,PK,1.09,-0.24,-0.92,-0.17
Columns,PK,-4.23,-4.01,-2.32,6.26
Columns,PK,-1.46,-1.53,9.83,5.73
Columns,PK,9.37,-1.32,1.27,-4.12
Columns,PK,5.84,-2.42,-5.21,1.07
Columns,PK,8.21,-9.36,-5.87,-3.21
Columns,PK,7.34,-7.3,-2.94,-5.86
Columns,PK,1.83,-2.77,1.47,-4.02
BlogsInd.,PK,14.39,-0.55,-5.42,-4.7
BlogsInd.,US,22.02,-1.39,2.5,-3.12
BlogsInd.,US,4.83,-3.58,5.34,9.22
BlogsInd.,US,-3.24,2.83,-5.3,-2.07
BlogsInd.,US,-5.69,15.17,-14.27,-1.62
BlogsInd.,US,-22.92,4.1,5.79,-3.88
BlogsNews,US,0.41,-2.03,-6.5,2.81
BlogsNews,US,-4.42,8.49,-8.04,2.04
BlogsNews,US,-10.72,-4.3,3.75,11.74
BlogsNews,US,-11.29,2.01,0.67,8.9
BlogsNews,US,-2.89,0.08,-1.59,7.06
BlogsNews,US,-7.59,8.51,3.02,12.33
BlogsNews,US,-7.45,23.51,2.79,0.48
BlogsNews,US,-12.49,15.79,-9.86,18.29
BlogsTech,US,-11.59,6.38,11.79,-7.28
BlogsTech,US,-4.6,4.12,7.46,3.36
BlogsTech,US,-22.83,2.54,10.7,5.09
BlogsTech,US,-4.83,3.37,-8.12,-0.9
BlogsTech,US,-14.76,29.21,6.23,9.33
Columns,US,-15.93,12.85,19.47,-0.88
Columns,US,-2.78,-1.52,8.16,0.24
Columns,US,-16.39,13.08,11.07,7.56
Even though I have tried to add detailed scale on y-axis, it is hard for me to pinpoint exact median score for each boxplot. So I need to print median value within each boxplot. There was another answer available (for faceted boxplot) which does not work for me as the printed values are not within the boxes but jammed together in the middle. It will be great to be able to print them within (middle and above the median line of) boxplots.
Thanks for your help.
Edit: I make a grouped graph as below.
Add
library(dplyr)
dims=dims%>%
group_by(Blog,Region)%>%
mutate(med=median(Dim1))
plotgraph <- function(x, y, colour, min, max)
{
plot1 <- ggplot(dims, aes(x = x, y = y, fill = Region)) +
geom_boxplot()+
labs(color='Region') +
geom_hline(yintercept = 0, alpha = 0.4)+
scale_y_continuous(breaks=c(seq(min,max,5)), limits = c(min, max))+
labs(x="Blog Type", y="Dimension Score") + scale_fill_grey(start = 0.3, end = 0.7) +
theme_grey()+
theme(legend.justification = c(1, 1), legend.position = c(1, 1))+
geom_text(aes(y = med,x=x, label = round(med,2)),position=position_dodge(width = 0.8),size = 3, vjust = -0.5,colour="blue")
return(plot1)
}
plot1 <- plotgraph (Blog, Dim1, Region, -30, 25)
Which gives (the text colour can be tweaked to something less tacky):
Note: You should consider using non-standard evaluation in your function rather than having it require the use of attach()
Edit:
One liner, not as clean I wanted it to be since I ran into problems with dplyr not properly aggregating the data even though it says the grouping was performed.
This function assume the dataframe is always called dims
library(ggplot2)
library(reshape2)
plotgraph <- function(x, y, colour, min, max)
{
plot1 <- ggplot(dims, aes_string(x = x, y = y, fill = colour)) +
geom_boxplot()+
labs(color=colour) +
geom_hline(yintercept = 0, alpha = 0.4)+
scale_y_continuous(breaks=c(seq(min,max,5)), limits = c(min, max))+
labs(x="Blog Type", y="Dimension Score") +
scale_fill_grey(start = 0.3, end = 0.7) +
theme_grey()+
theme(legend.justification = c(1, 1), legend.position = c(1, 1))+
geom_text(data= melt(with(dims, tapply(eval(parse(text=y)),list(eval(parse(text=x)),eval(parse(text=colour))), median)),varnames=c("Blog","Region"),value.name="med"),
aes_string(y = "med",x=x, label = "med"),position=position_dodge(width = 0.8),size = 3, vjust = -0.5,colour="blue")
return(plot1)
}
plot1 <- plotgraph ("Blog", "Dim1", "Region", -30, 25)
Assuming that Blog is your dataframe, the following should work:
min <- -30
max <- 25
meds <- aggregate(Dim1~Region, Blog, median)
plot1 <- ggplot(Blog, aes(x = Region, y = Dim1, fill = Region)) +
geom_boxplot()
plot1 <- plot1 + labs(color='Region') + geom_hline(yintercept = 0, alpha = 0.4)
plot1 <- plot1 + scale_y_continuous(breaks=c(seq(min,max,5)), limits = c(min, max))
plot1 <- plot1 + labs(x="Blog Type", y="Dimension Score") + scale_fill_grey(start = 0.3, end = 0.7) + theme_grey()
plot1 + theme(legend.justification = c(1, 1), legend.position = c(1, 1)) +
geom_text(data = meds, aes(y = Dim1, label = round(Dim1,2)),size = 5, vjust = -0.5, color='white')

ggplot2 and facet_grid : add highest value for each plot

I am using facet_grid() to plot multiple plot divided per groups of data. For each plot, I want to add in the corner the highest value of the Y axis. I've tried several hacks but it never gives me the expected results. This answer partially helps me but the value I want to add will constantly be changing, therefore I don't see how I can apply it.
Here is a minimal example, I'd like to add the red numbers on the graph below:
library(ggplot2)
data <- data.frame('group'=rep(c('A','B'),each=4),'hour'=rep(c(1,2,3,4),2),'value'=c(5,4,2,3,6,7,4,5))
ggplot(data,aes(x = hour, y = value)) +
geom_line() +
geom_point() +
theme(aspect.ratio=1) +
scale_x_continuous(name ="hours", limits=c(1,4)) +
scale_y_continuous(limits=c(1,10),breaks = seq(1, 10, by = 2))+
facet_grid( ~ group)
Thanks for your help!
library(dplyr)
data2 <- data %>% group_by(group) %>% summarise(Max = max(value))
ggplot(data,aes(x = hour, y = value)) +
geom_line() +
geom_point() +
geom_text(aes(label = Max), x = Inf, y = Inf, data2,
hjust = 2, vjust = 2, col = 'red') +
theme(aspect.ratio=1) +
scale_x_continuous(name ="hours", limits=c(1,4)) +
scale_y_continuous(limits=c(1,10),breaks = seq(1, 10, by = 2))+
facet_grid( ~ group)
This does the trick. If you always have fixed ranges you can position the text manually.
library(ggplot2)
data <- data.frame('group'=rep(c('A','B'),each=4),'hour'=rep(c(1,2,3,4),2),'value'=c(5,4,2,3,6,7,4,5))
ggplot(data,aes(x = hour, y = value)) +
geom_line() +
geom_point() +
geom_text(
aes(x, y, label=lab),
data = data.frame(
x=Inf,
y=Inf,
lab=tapply(data$value, data$group, max),
group=unique(data$group)
),
vjust="inward",
hjust = "inward"
) +
theme(aspect.ratio=1) +
scale_x_continuous(name ="hours", limits=c(1,4)) +
scale_y_continuous(limits=c(1,10),breaks = seq(1, 10, by = 2))+
facet_grid( ~ group)

Getting a bar plot with error bars in ggplot2 to expand above error bars whilst also keeping the origin at y=0 [duplicate]

How do you adjust the expansion of limits asymmetrically in ggplot? For example,
library(ggplot2)
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1)
I would like the bottom of the bars flush with the bottom of the panel background, but would still like space at the top. I can achieve this with a blank annotation:
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
annotate("blank", x = 4, y = 16) +
scale_y_continuous(expand = c(0.0,0))
In previous versions of ggplot, however, I could use the solution provided by Rosen Matev:
library("scales")
scale_dimension.custom_expand <- function(scale, expand = ggplot2:::scale_expand(scale)) {
expand_range(ggplot2:::scale_limits(scale), expand[[1]], expand[[2]])
}
scale_y_continuous <- function(...) {
s <- ggplot2::scale_y_continuous(...)
class(s) <- c('custom_expand', class(s))
s
}
and then use scale_y_continuous(expand = list(c(0,0.1), c(0,0))) which would add a consistently addition to the top of the chart. In the current version, however, I get an error
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
scale_y_continuous(expand = list(c(0,0.1), c(0,0)))
# Error in diff(range) * mul : non-numeric argument to binary operator
Is there an effective solution for ggplot2 2.0?
A solution should include the ability to work flexibly with facets, and free_xy scale options. For example,
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y")
A solution should provide something like:
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y") +
scale_y_continuous(expand = c(0,0)) +
geom_blank(data = data.frame(cyl = c(5,5), y = c(12, 16), vs = c(1,0)), aes(x = cyl, y = y))
ggplot2 v3.0.0 released in July 2018 has expand_scale() option (w/ mult argument) to achieve OP's goal.
Edit: expand_scale() will be deprecated in the future release in favor of expansion(). See News for more information.
library(ggplot2)
### ggplot <= 3.2.1
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y") +
scale_y_continuous(expand = expand_scale(mult = c(0, .2)))
### ggplot >= 3.2.1.9000
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y") +
scale_y_continuous(expand = expansion(mult = c(0, .2)))
I have now tried to add code for this to ggplot2; see issue #1669 and the corresponding pull request. If it is accepted, the syntax for the expand argument will been changed from c(m, a) to c(m_lower, a_lower, m_uppper, a_upper), for specifying separate expansion values for the lower and upper range limits. (The old syntax will still continue to work, though, as the first two elements will be reused if elements three and/or four are missing.)
With this new syntax, you can use
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
scale_y_continuous(expand = c(0, 0, 0.05, 0))
The result looks like this:
It also works with facetting:
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y") +
scale_y_continuous(expand = c(0, 0, 0.05, 0))
I used Rosen Matev's solution often, and was disappointed when it broke with ggplot version 2.0. I offer a solution, though not nearly as elegant as Rosen's, but will work on plots with no facetting, facet_wrap, and facet_grid, and with one-way and two-way facet_grid. However, it will not work with more complicated facet grids, nor will it work with coord_flip. There are two functions: one for asymmetric expansion along the y-axis, and one for expansion along the x-axis. The functions perform multiplicative and additive expansions.
The functions gather information from the plot, calculate new limits for the y (or x) axis, then use geom_blank to construct new plots with the desired expansion factors.
First, a function to perform asymmetric expansion along the y-axis.
# Function takes two parameters
# 'p' is the plot
# 'expand' is a list of two vectors:
# First vector contains the multiplicative factors;
# Second vector contains the additive parts.
# First element in each vector refers to the lower boundary;
# Second element refers to the upper boundary.
asymmY = function(p, expand = list(mult = c(0, .2), add = c(0, 0))) {
np = p + coord_cartesian(expand = FALSE) # No expand
gb <- ggplot_build(np)
limits <- sapply(gb$panel$ranges, "[[", "y.range")
range = apply(limits, 2, function(x) max(x) - min(x))
rangeU = range*expand[[1]][2]
rangeL = range*expand[[1]][1]
limits <- limits + rbind(-rangeL, rangeU) # Multiplicative expand
limits[1,] = limits[1,] - expand[[2]][1] # Additive expand
limits[2,] = limits[2,] + expand[[2]][2]
limits = as.vector(limits)
df = facet_type(np, gb, "y", limits) # df with new limits - depends on facet type
np = np + geom_blank(data = df, inherit.aes = FALSE, aes(x = Inf, y = y)) # new plot
# But the x axis expansions were set to false. Put back the default expand
gb <- ggplot_build(np)
if(any(grepl("Discrete", class(gb$panel$x_scale[[1]])))) {
limits <- sapply(gb$panel$ranges, "[[", "x.range")
limits[1,] = ceiling(limits[1,]) - .6
limits[2,] = trunc(limits[2,]) + .6
limits = as.vector(limits)
} else {
limits <- sapply(gb$panel$ranges, "[[", "x.range")
range = apply(limits, 2, function(x) max(x) - min(x))
rangeU = range*.05
rangeL = range*.05
limits <- limits + rbind(-rangeL, rangeU)
limits = as.vector(limits)
}
df = facet_type(np, gb, "x", limits)
np + geom_blank(data = df, inherit.aes = FALSE, aes(x = x, y = Inf))
}
# Function to determine type of facetting
# and to get data frame of new limits.
facet_type = function(np, gb, axis, limits) {
if(class(np$facet)[1] == "null") {
setNames(data.frame(y = limits), axis)
} else
if(class(np$facet)[1] == "wrap") {
facetvar <- as.character(np$facet$facets)
facetlev <- gb$panel$layout[[facetvar]]
setNames(data.frame(rep(facetlev, each = 2), limits), c(facetvar, axis))
} else {
facetvar <- as.character(np$facet$cols)
if(length(facetvar) == 0) facetvar <- as.character(np$facet$rows)
facetlev <- gb$panel$layout[[facetvar]]
setNames(data.frame(rep(facetlev, each = 2), limits), c(facetvar, axis))
}
}
Try it out with some facet wrap and facet grid plots.
# Try asymmetric expand along y-axis
library(ggplot2)
p1 <- ggplot(mtcars) +
geom_bar(aes(x = factor(cyl))) +
facet_grid(am ~ vs , scales = "free_y")
p2 <- ggplot(mtcars) +
geom_bar(aes(x = factor(cyl), fill = factor(vs)), width = .5) +
facet_grid(vs ~ ., scales = "free_y")
p3 <- ggplot(mtcars) +
geom_bar(aes(x = factor(cyl), fill = factor(vs)), width = .5) +
facet_grid(. ~ vs)
p4 <- ggplot(mtcars) +
geom_bar(aes(x = factor(cyl), fill = factor(vs)), width = .5) +
facet_wrap(~vs, scales = "free_y")
asymmY(p1, list(c(0, 0.1), c(0, 0)))
asymmY(p2, list(c(0, 0.1), c(0, 0)))
asymmY(p3, list(c(0, 0.1), c(0, 0)))
asymmY(p4, list(c(0, 0.1), c(0, 0)))
Second, a function to perform asymmetric expansion along the x-axis.
asymmX = function(p, expand = list(mult = c(0, .2), add = c(0, 0))) {
np = p + coord_cartesian(expand = FALSE) # No expand
gb <- ggplot_build(np)
limits <- sapply(gb$panel$ranges, "[[", "x.range")
range = apply(limits, 2, function(x) max(x) - min(x))
rangeU = range*expand[[1]][2]
rangeL = range*expand[[1]][1]
limits <- limits + rbind(-rangeL, rangeU) # Mult expand
limits[1,] = limits[1,] - expand[[2]][1]
limits[2,] = limits[2,] + expand[[2]][2] # Add expand
limits = as.vector(limits)
df = facet_type(np, gb, "x", limits) # df with new limits - depends on facet type
np = np + geom_blank(data = df, inherit.aes = FALSE, aes(x = x, y = Inf)) # new plot
# But the y axis expansions were set to false. Put back the default expand
gb <- ggplot_build(np)
if(any(grepl("Discrete", class(gb$panel$y_scale[[1]])))) {
limits <- sapply(gb$panel$ranges, "[[", "y.range")
limits[1,] = ceiling(limits[1,]) - .6
limits[2,] = trunc(limits[2,]) + .6
limits = as.vector(limits)
} else {
limits <- sapply(gb$panel$ranges, "[[", "y.range")
range = apply(limits, 2, function(x) max(x) - min(x))
rangeU = range*.05
rangeL = range*.05
limits <- limits + rbind(-rangeL, rangeU)
limits = as.vector(limits)
}
df = facet_type(np, gb, "y", limits)
np + geom_blank(data = df, inherit.aes = FALSE, aes(x = Inf, y = y))
}
Try it out.
# Try asymmetric expand along x-axis
df = data.frame(x = c(20, 15, 25, 23, 12, 14),
y = rep(c("a", "b", "c"), 2),
z = rep(c("aaa", "bbb"), each = 3),
w = rep(c("ccc", "ddd", "eee"), each = 2))
p1 = ggplot(df[,-4]) + geom_point(aes(x, y)) +
geom_segment(aes(x = 0, xend = x, y = y, yend = y)) +
geom_text(aes(x = x, y = y, label = x), hjust = -1) +
facet_grid(. ~ z, scales = "free_x")
p2 = ggplot(df[, -4]) + geom_point(aes(x, y)) +
geom_segment(aes(x = 0, xend = x, y = y, yend = y)) +
geom_text(aes(x = x, y = y, label = x), hjust = -1) +
facet_grid(z ~ .)
p3 = ggplot(df) + geom_point(aes(x, y)) +
geom_segment(aes(x = 0, xend = x, y = y, yend = y)) +
geom_text(aes(x = x, y = y, label = x), hjust = -1) +
facet_grid(w ~ z)
p4 = ggplot(df[,-4]) + geom_point(aes(x, y)) +
geom_segment(aes(x = 0, xend = x, y = y, yend = y)) +
geom_text(aes(x = x, y = y, label = x), hjust = -1) +
facet_wrap(~ z)
asymmX(p1, list(c(0, .15), c(0, 0)))
asymmX(p2, list(c(0, 0), c(0, 5)))
asymmX(p3, list(c(0, .2), c(0, 0)))
asymmX(p4, list(c(0, 0), c(9, 5)))

Resources