Question

I want to both transform the exponent notation of ggplot2 axis labels and apply a transformation. The labels=commma gives me regular, non-exponent numbers, but I would like to add a transformation so the y axis ticks are in the thousands, not millions.

library(ggplot2)
library(scales)
fy <- c("FY09 Q4", "FY09 Q3", "FY09 Q2", "FY09 Q1")
views <- c(15881100,  8888000, 24168000, 17611000)
df <- data.frame(FY=fy, views=views)
g <- ggplot(df, aes(x=FY, y=views))
g <- g + geom_bar(stat="identity")
g <- g + scale_y_continuous(labels = comma)
print(g)
Was it helpful?

Solution

Your question isn't clear, but there are a couple of ways you could do this. I wouldn't bother messing around with the breaks, I would transform the data or augment it so that the breaks look after themselves. That is, I would keep the breaks and the data consistent.

screenshot

library(ggplot2)
library(scales)
df <- data.frame(FY = c("FY09 Q4", "FY09 Q3", "FY09 Q2", "FY09 Q1"),
                 views = c(15881100,  8888000, 24168000, 17611000))
df$views.k <- df$views/1000

# Transform y in the ggplot call...
g <- ggplot(df, aes(x = FY, y = views/1000)) +
    geom_bar(stat = "identity") +
    scale_y_continuous(labels = comma)
print(g)

# ...or just use views.k
g <- ggplot(df, aes(x = FY, y = views.k)) +
    geom_bar(stat="identity") +
    scale_y_continuous(labels = comma)
print(g)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top