Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ChrisHarrod/485c2f5f505ec918df1401e9eb123e06 to your computer and use it in GitHub Desktop.

Select an option

Save ChrisHarrod/485c2f5f505ec918df1401e9eb123e06 to your computer and use it in GitHub Desktop.
ggplot Secondary Axis Demo
library(ggplot)
data <- data.frame(a = c(rnorm(100,1,0.1),rnorm(10,1.2,0.2)),
b = c(rnorm(100,8,2),rnorm(10,13,2)),
c = c(rep("Group1",100),rep("Group2",10)))
data$c_dummy = ifelse(data$c == "Group1",0.5,1.5)
ggplot(data,aes(x=c_dummy,y=a,group=c)) +
geom_boxplot() +
geom_jitter(aes(size=b),width=0.1) +
scale_y_continuous(sec.axis = dup_axis(),
limits = c(0.5,2.0),
n.breaks = 4,
expand = expansion(0,0)) +
scale_x_continuous(expand = expansion(add = c(0.75)),
sec.axis = dup_axis(),
breaks = c(0.5,1.5),
labels=unique(data$c)) +
scale_size_continuous(range = c(0.05,4),breaks = seq(6,16,2)) +
guides(size = guide_legend(reverse = T)) +
theme_classic() +
theme(panel.background = element_rect(color="black"),
legend.position = c(0.25,0.75),
axis.ticks.length.y = unit(-5,"mm"),
plot.margin = margin(8,8,2,2,"mm"),
axis.ticks.length.x = unit(-5,"mm"),
axis.title.y.right = element_blank(),
axis.text.x.bottom = element_text(margin = margin(20,0,0,0)),
axis.text.y.left = element_text(margin = margin(0,7,0,0,"mm")),
axis.text.x.top = element_blank(),
axis.title.x.top = element_blank(),
axis.text.y.right = element_blank())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment