Arch Arch - 1 month ago 6
R Question

Displaying Axis Percentages in ggplot2 without: `scale_y_continuous(labels=percent)`

I would like to display percents on the Y-Axis. It appears the most common method of doing this is in ggplot2 is via scales:

scale_y_continuous(labels=percent)
.

I am unable to use this method because I am implementing
labels=every_nth
, a custom function to display minor tick marks on the Y axis

library(ggplot2)
library(scales)

ggplot(all_mydata, aes(x=dose,y=probability, group=model))+
geom_point(aes(col=model, shape=model))+


#X-Axis transformation:
annotation_logticks(scaled = TRUE,sides="b") +
scale_x_log10(breaks = 10^(-1:10),
labels = trans_format("log10", math_format(10^.x)))+



#Y axis minor ticks using "every_nth", for minor ticks.
scale_y_continuous(breaks=seq(0,1,0.05),
labels=every_nth(seq(0,1,0.05),2,inverse=TRUE))

# scale_y_continuous(labels=percent) #conflicts with previous scale_y_continuous call


enter image description here

data - not extremely relevant to this case

all_mydata<-structure(list(dose = c(3, 3, 25, 25, 25, 50, 50, 50), total = c(25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L), affected = c(1L, 3L, 22L,
14L, 22L, 23L, 16L, 21L), probability = c(0.04, 0.12, 0.88, 0.56,
0.88, 0.92, 0.64, 0.84), model = c("mod1", "mod1", "mod1", "mod1",
"mod1", "mod1", "mod1", "mod1")), .Names = c("dose", "total",
"affected", "probability", "model"), row.names = c(1L, 2L, 51L,
52L, 53L, 73L, 74L, 75L), class = "data.frame")


Custom Function, found on stack exchange which draws minor tick marks on Y axis

every_nth <- function(x, nth, empty = TRUE, inverse = FALSE)
{
if (!inverse) {
if(empty) {
x[1:nth == 1] <- ""
x
} else {
x[1:nth != 1]
}
} else {
if(empty) {
x[1:nth != 1] <- ""
x
} else {
x[1:nth == 1]
}
}
}

Answer

For example, you can change your every_nth function to something like that:

every_nth <- function(x, nth, empty = TRUE, inverse = FALSE) 
{
    if (!inverse) {
        if(empty) {
            x[1:nth == 1] <- ""
            out <- x
        } else {
            out <- x[1:nth == 1]
        }
    } else {
        if(empty) {
            x[1:nth != 1] <- ""
            out <- x

        } else {
            out <- x[1:nth == 1]
        }
    }
    out2 <- paste0(100*as.numeric(out), "%")
    out2[out2 == "NA%"] <- ""
    out2
}