Adjusting the y-tick labels with hjust not working - r

I want to move the y-axis tick labels to the left (as i did with the axis.text.y to the bottom).
The weird thing is with hjust = -2.5, although the theme_set() part runs without errors, the text on the y-axis does not get moved. However, vjust = 2does affect the y labels just fine.
I am creating a bug with all my options in the theme?
library(tidyverse)
library(ggplot2)
theme_set(
theme_classic() +
theme(
axis.ticks.length = unit(-0.25, "cm"),
axis.text.x = element_text(vjust = -2.5),
axis.text.y = element_text(hjust = -2.5), # this does not do anything.
# axis.text.y = element_text(vjust = -2.5), # while vjust does affect the text placement.
axis.line = element_blank(),
panel.grid.major.y = element_line(linetype = 2),
plot.title = element_text(hjust = 0.5),
text = element_text(family = "serif"),
legend.justification = c(1, 1),
legend.position = c(1, 1),
panel.border = element_rect(fill = NA, size = 2)))
mpgdat <- tibble(mtcars)
mpgdat %>% ggplot(aes(disp, mpg)) + geom_point()

This does seem to be a bug in how hjust works for axis text. A workaround would be to use margin instead of hjust:
theme_set(
theme_classic() +
theme(
axis.ticks.length = unit(-0.25, "cm"),
axis.text.x = element_text(vjust = -2.5),
axis.text.y = element_text(margin = unit(c(0,0.4,0,0), "cm")),
panel.border = element_rect(fill = NA, size = 2)))
'
Hat tip to this related answer: How do I make my axis ticks face Inwards in ggplot2

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))

How do I print a plot with only keep the plot panel content in ggplot2?

I want to save a picture from a plot which only retains the plot panel contents.
But when I used the below code, there's a white margin at the left and bottom of the plot.
How do I get rid of it?
Thanks.
ggplot()+
stat_function(fun = ~ -(.x-2) ^ 2 + 3, size = .5, linetype = 'dashed', color='white') +
scale_x_continuous(expand = c(0, 0), limits = c(0, 4)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 4)) +
theme(
plot.margin = unit(c(0,0,0,0), "pt"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = "black", colour = "black"),
axis.text = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank()
)

How to change the position of one of the facet_nested labels?

I have a plot for which I would like to place one facet label in the top and the other one on the left side of the plot. However, I don't know if that is possible or if I should do it in an other way. Below I show a fake example to play with:
library(ggplot2)
library(ggsci)
library(ggthemes)
library(ggh4x)
df <- data.frame(x=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28),
y=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28))
df$Method <- "Pearson"
df$ID <- "A"
Plot <- ggplot(df, aes(x=x, y=y)) +
geom_point(size=.8) +
theme_hc() +
theme(strip.background = element_rect(colour = "black", fill = "white",
size = 1.5, linetype = "solid"),
axis.title.x =element_blank(),
axis.title.y =element_blank(),
axis.text.x = element_text(angle = 0, hjust = 0.5,size = 10.5, face="bold"),
axis.text.y = element_text(angle = 0, hjust = 0.5,size = 10.5),
strip.text.x = element_text(size = 9),
strip.text.y = element_text(size = 13),
axis.line = element_line(),
panel.grid.major= element_blank(),
panel.grid.minor = element_blank(),
legend.text=element_text(size=9),
legend.title = element_text(size=10,face="bold"),
legend.key=element_blank(),
legend.justification = c(0.5,0),
legend.position = "right",
panel.border = element_blank(),
strip.placement = "outside",
plot.title = element_text(size = 16, hjust = 0.5),
strip.switch.pad.grid = unit('0.1', "cm")) +
labs(x= '\nTime delay (modifiable device)',y=expression(R^{2})) +
guides(color=guide_legend(override.aes=list(fill=NA))) +
scale_y_continuous(limits = c(0., 30), breaks = c(5, 15,25)) +
facet_wrap(Method~ID) +
scale_color_jco()
Plot
I would like to place the A label in the left part of the plot? Does anyone know how to do it?
Thanks
I'm sorry for stripping away most of the plotting code, but the following captures the essence and requires less additional packages.
facet_wrap() only puts strips on one side of the plot. If you need two sides with strips, you can use facet_grid(). To place the strip on the left, you can use the switch = 'y' argument.
library(ggplot2)
df <- data.frame(x=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28),
y=c(0,0,0.3,0.8,1.5,3,5,7,9,13,15,20,28))
df$Method <- "Pearson"
df$ID <- "A"
ggplot(df, aes(x=x, y=y)) +
geom_point(size=.8) +
facet_grid(Method~ID, switch = 'y')

How to move legend up closer to the x-axis label in ggplot2

I have am creating a function to create dumbbell graphs with the legend positioned on the bottom. However, it's too far away from the title of the x-axis. I wanted to move it up slightly so that it is 10 pixels below the x-axis.
Here's the code:
vertical_theme = theme_bw(base_family = "Georgia") +
theme(
panel.border = element_rect(color = "black", fill=NA),
axis.title.x = element_text(hjust=0.5, size = 10, margin=margin(t=10, b=10)),
axis.text.y = element_text(size=10, margin=margin(r=10), color="black", hjust=0),
axis.text.x = element_text(size=10, margin=margin(t=10), color="black"),
axis.title.y = element_blank(),
legend.title = element_blank(),
legend.position= "bottom",
legend.text = element_text(size = 10, margin = margin(r = 10)),
panel.grid.major.y = element_blank() ,
panel.grid.minor.y = element_blank(),
panel.grid.major.x = element_line(size=1),
panel.grid.minor.x = element_blank(),
plot.margin = margin(10, 30, 10, 10, "pt"))
dumbbell = function(df) {
ggplot(df, aes(pct_responses, Domain)) +
geom_line(aes(group=Domain)) +
geom_point(aes(shape=race), size=5, color="#3bbae0" ) +
vertical_theme +
scale_shape_manual(labels = c("Black Students", "White Students"),
values=c(15, 19)) +
scale_x_continuous(expand = c(0, 0),
limits=c(0,100),
breaks = seq(0, 100, by=20),
labels = function(x) paste0(x,"%")) +
labs(x = "% of Responses") +
scale_y_discrete(labels = wrap_format(40))
}
dumbbell(df)
Here's a screenshot (labels on y-axis removed because that data isn't public yet):
I tried to adjust the legend.position manually with legend.position = c(0.5, 0) (playing around with various different numbers) but then the legend overlaps with "% of Responses."
Use theme(legend.margin=margin(-10, 0, 0, 0)) to move the legend up. Adjust -10 as needed.

ggplot2 geom_bar: Centering bars

I would really appreciate help with a ggplot2 issue. I've been looking around it for long, so my best chance is now here. I provide a reproducible script.
What I'd need to do is center the bars horizontally. For now, they polarise towards the sides--especially notably on the 2009 and 2012 bars.
Centering them would allow me to freely adjust their width, whereas now I cannot.
This is the current, self-contained code:
install.packages('ggplot2')
library(ggplot2)
# Data
Year = c('2009','2009','2009','2009','2010','2010','2010','2010','2011','2011','2011','2011','2012','2012','2012','2012')
City = c('Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius',
'Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius','Kaunas','Vilnius')
Busy = c('Peak', 'Peak', 'Off-peak', 'Off-peak', 'Peak', 'Peak', 'Off-peak', 'Off-peak', 'Peak', 'Peak', 'Off-peak',
'Off-peak', 'Peak', 'Peak', 'Off-peak', 'Off-peak')
Result = c(-0.417277550641143, 0.540415934506096, -0.887323992801467, -1.0016151369497, -1.69512596882652,
-0.474180286913426, -1.87972395432173, -1.55647964460481, -1.10385766877877, -3.19261229467907,
-2.11137007243349, -3.24910554029829, -0.949278709972917, -2.22558030912235, -1.3496651478542, -2.59961942855099)
pvalue.asterisks = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, '*', NA, '*', NA, NA, NA, NA)
Results = data.frame(Year, City, Busy, Result, pvalue.asterisks)
str(Results)
Results
# Plot
ggplot(Results, aes(Year, Result, fill=City)) +
ylab(expression(paste(italic('t'), '-value'))) +
facet_grid(list('Busy', 'Year')) + scale_fill_grey(start = 0, end = .6) +
geom_bar(width=2.9, stat = "identity", position = position_dodge(width = 3)) +
scale_y_continuous(expand = c(.035,0)) + scale_x_discrete(expand = c(.7,.4)) +
theme( axis.title.x=element_blank(), axis.text.x = element_blank(),
axis.title.y = element_text(size=19, face="bold", margin = margin(0, 3, 0, 0)),
axis.text.y = element_text(size = 13),
legend.title = element_blank(), legend.text = element_text(size=17),
legend.background = element_rect(fill="white", size=0.1, linetype="solid"),
legend.key.size = unit(1.7,"line"), axis.ticks.x=element_blank(), legend.position = c(.167, .6),
panel.background = element_blank(), plot.title = element_blank(),
legend.margin=margin(c(-.05,.14,.11,.1), unit='cm'),
panel.grid.major.y = element_line(colour = "grey90"),
panel.grid.major.x = element_blank(), plot.margin = unit(c(.05, .1, 0, .1), 'cm'),
strip.text.x = element_text(face='bold', size=15, margin = margin(.2, 0, .2, 0, "cm")),
strip.text.y = element_text(face='bold', size=15, margin = margin(0, .2, 0, .2, "cm")),
strip.background = element_rect(colour="grey48", fill='grey95'), panel.spacing = unit(.08, "lines")) +
geom_text(aes(x=Year, y=Result, label=pvalue.asterisks), vjust=-.01, colour= 'white', size=15, hjust=-.168 )
-- Thank you very much
You just need to add scales = 'free_x' to your script. You can also replace geom_bar(stat = 'identity') with geom_col()
Relevant info taken from ?facet_grid
scales: Are scales shared across all facets (the default, "fixed"), or do they vary across rows ("free_x"), columns ("free_y"), or both rows and columns ("free")?
p1 <- ggplot(Results, aes(Year, Result, fill=City)) +
ylab(expression(paste(italic('t'), '-value'))) +
facet_grid(rows = vars(Busy), cols = vars(Year), scales = 'free_x') +
scale_fill_grey(start = 0, end = .6) +
geom_col(position = position_dodge(width = 0.9)) +
scale_y_continuous(expand = c(.035,0)) +
scale_x_discrete(expand = c(.7,.4))
p1 +
theme( axis.title.x=element_blank(), axis.text.x = element_blank(),
axis.title.y = element_text(size=19, face="bold", margin = margin(0, 3, 0, 0)),
axis.text.y = element_text(size = 13),
legend.title = element_blank(), legend.text = element_text(size=17),
legend.background = element_rect(fill="white", size=0.1, linetype="solid"),
legend.key.size = unit(1.7,"line"), axis.ticks.x=element_blank(), legend.position = c(.167, .6),
panel.background = element_blank(), plot.title = element_blank(),
legend.margin=margin(c(-.05,.14,.11,.1), unit='cm'),
panel.grid.major.y = element_line(colour = "grey90"),
panel.grid.major.x = element_blank(), plot.margin = unit(c(.05, .1, 0, .1), 'cm'),
strip.text.x = element_text(face='bold', size=15, margin = margin(.2, 0, .2, 0, "cm")),
strip.text.y = element_text(face='bold', size=15, margin = margin(0, .2, 0, .2, "cm")),
strip.background = element_rect(colour="grey48", fill='grey95'), panel.spacing = unit(.08, "lines")) +
geom_text(aes(x=Year, y=Result, label=pvalue.asterisks), vjust=-.01, colour= 'white', size=15, hjust=-.168 )
#> Warning: Removed 14 rows containing missing values (geom_text).
Created on 2018-09-20 by the reprex package (v0.2.1.9000)
If you remove the theme stuff you will see the problem, the X axis is years, and it's attempting to plot each one on the x-value for that year. One way to fix this is to set the scales parameter to facet_grid to be "free_x".
facet_grid(list('Busy', 'Year'), scales="free_x")
and then you only have to adjust the sizing of the bars.
geom_bar(width=0.5, stat = "identity", position = "dodge")

Resources