Eric Dilley
Eric Dilley

Reputation: 337

R how to place text on ggplot relative to axis

I am attempting to use geom_text() in ggplot to place sample sizes on a bar chart with defined limits determined by ggplot. For most of my plots, I have been able to get away with specifying the y-value for text placement as 0. However, for a few plots, the CI bars extend below 0.

enter image description here

In order to prevent printing the sample sizes on the CI bars, I want to generate code that specifies the y-value for geom_text() in relation to the plot margin that defines the x-axis. The idea would to generate general code relative to the x-axis so this code can be applied to all my plots regardless of where the minimum value of y is in the plot. Ideally, I would like to tweak my plot code to achieve this if possible. Thanks in advance for your input!

Plot Database

data <- structure(list(Site_long = structure(c(2L, 2L, 1L, 1L), .Label = c("Hanauma Bay", 
"Waikiki"), class = "factor"), Shelter = structure(c(1L, 2L, 
1L, 2L), .Label = c("Low", "High"), class = c("ordered", "factor"
)), mean = c(0.096818329015544, 0.140368187765273, 0.364490168863912, 
0.452663275851282), sd = c(0.358269615215823, 0.442381836749624, 
0.431417057945072, 0.461599742148954), lower = c(-0.13725115292546, 
-0.148654612244481, 0.198658790631641, 0.337761753133984), upper = c(0.330887810956549, 
0.429390987775027, 0.530321547096184, 0.56756479856858), sample_size = c(9L, 
9L, 26L, 62L)), row.names = c(NA, -4L), groups = structure(list(
    Site_long = structure(1:2, .Label = c("Hanauma Bay", "Waikiki"
    ), class = "factor"), .rows = structure(list(3:4, 1:2), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

Plot Code

mult_compare_growth_all <- c("AB", "B", "A", "AB")

growth_plot <- ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_bar(position = "dodge", stat="identity", width = .8) +
  scale_x_discrete(limits = position) +
  geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = data$upper), vjust = -.5, position = position_dodge(width = 0.8), size = 4) +
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none", 
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

Upvotes: 2

Views: 2475

Answers (3)

brian avery
brian avery

Reputation: 413

for some reason when I plot this, mine is reversed (probably factor order), but I think this is what you want?

ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_col(aes(fill=Shelter), position = "dodge", width = 0.8) + 
  geom_text(aes(y=lower, group=Shelter, label = sample_size), 
            position = position_dodge(width = 0.8), vjust=1.5) +
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = data$upper), vjust = -.5, 
            position = position_dodge(width = 0.8), size = 4) +
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none", 
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

results: enter image description here

Let me break this down a little:

I used geom_col() since it is built for this kind of bar plot with the height specified by a single value. It can also be done with geom_bar() the way you did.

Then in geom_text() you need the group aesthetic in there to put labels on correct bars, and you have to specify y=lower which puts the label exactly (annoyingly) on the bottom of error bar, but vjust moves it down. The value (1.5) probably has some meaning but I don't know what it is and I had to fiddle with it so that part isn't automatic.

Upvotes: 0

rodolfoksveiga
rodolfoksveiga

Reputation: 1261

You can use y = -Inf to orient the text position. In order to keep the text inside the plot, you must couple a vjust factor with Inf, otherwise, the text will fall out of the plot.

Here is the code:

ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_bar(position = "dodge", stat = "identity", width = .8) +
  geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = data$upper), vjust = -.5,
            position = position_dodge(width = .8), size = 4) +
  geom_text(aes(label = sample_size, y = -Inf), vjust = -.3,
            position = position_dodge(width = .8)) +
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none", 
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

And the output:

enter image description here

Let me know if this is what you are looking for.

Upvotes: 1

Duck
Duck

Reputation: 39613

Maybe as a suggestion you could compute a placement factor pf based on the minimun value of your lower variable and add some adjustment quantity like this:

library(ggplot2)
#Plot
mult_compare_growth_all <- c("AB", "B", "A", "AB")
#Factor for placement
pf <- min(data$lower)-0.02
#Code
ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_bar(position = "dodge", stat="identity", width = .8) +
  geom_text(aes(y=pf,label=sample_size),position = position_dodge(0.8))+
  geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = upper),
            vjust = -.5, position = position_dodge(width = 0.8), size = 4)+
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none",
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

Output:

enter image description here

Upvotes: 1

Related Questions