Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - changing numeric axis title to vector of strings

So far I have the following from my ggplot compilation:

enter image description here

And I got the axis just right this time ... with the following code snippet:

p<- p + ylim(c(0,100))
p<- p + geom_hline(aes(yintercept=0))

p<- p + scale_x_continuous(breaks = c(seq(1940,1985,by=5)))
p

so I have an x-axis from 1940-1985 by steps of 5 and a y-axis from 0-100 by steps of 20 ...

The first question

How do I make the 100 appear on the y-axis?

The second question

How do I change my x-labels into the following string vectors?

abbrev_x <- c("1940","'45","'50","'55","'60","'65","'70","'75","'80","'85")
abbrev_y <- c("0","20","40","60","80","100%")

So, the best solution I've found revolves around scale_x_continuous, which the following code snippet example suggests work with already pre-existing string axis labels:

p + scale_x_discrete(limit = c("I1", "SI2", "SI1"),
                 labels = c("Ione","SItwo","SIone"))

enter image description here

This is certainly an issue, as what I want to write is the following:

abbrev_x <- c("1940","'45","'50","'55","'60","'65","'70","'75","'80","'85")
abbrev_y <- c("0","20","40","60","80","100%")
p<- p + scale_x_continuous(breaks = abbrev_x)
p<- p + scale_y_continuous(breaks = abbrev_y)
p

But this seems to be a fictitious reality in my world right now. To justify this fiction, here is the following error code, among others as I tweak:

Error in x - from[1] : non-numeric argument to binary operator

Any thoughts?

like image 853
bmc Avatar asked Feb 08 '17 02:02

bmc


1 Answers

You need two parameters to label continuous axis correctly:

  • breaks: specify where to place the labels
  • labels: specify what labels to put on axis

in the scale_x/y_continuous function:

Example data frame:

df <- data.frame(YearOfBirth = seq(1940,1985,by=5), AverageProbability = runif(10) * 100)

abbrev_x <- c("1940","'45","'50","'55","'60","'65","'70","'75","'80","'85")
abbrev_y <- c("0","20","40","60","80","100%")

ggplot(df, aes(x = YearOfBirth, y = AverageProbability)) + 
    geom_line(col = "burlywood3") + 
    scale_x_continuous(breaks = seq(1940,1985,by=5), labels = abbrev_x) + 
    scale_y_continuous(breaks = (0:5)*20, labels = abbrev_y, limits = c(0, 110))

enter image description here

like image 118
Psidom Avatar answered Oct 31 '22 14:10

Psidom