Customize axis labels

RGgplot2

R Problem Overview


I have a simple geom_point plot, in which the x variable is ordinal, taking 5 values (coded 1:5).

In the plot I would like to replace it with 5 corresponding text labels. Is it possible to do it in ggplot?

R Solutions


Solution 1 - R

You should be able to do this with scale_x_discrete.

library(ggplot2)
df <- data.frame(x = 1:5, y = sample(1:10, 5, TRUE))

qplot(factor(x),y, data = df) + 
scale_x_discrete(breaks = 1:5, labels=c("foo","bar","baz","phi","fum")) +
xlab(NULL)

Solution 2 - R

scale_x_discrete should do it:

x <- sample(1:5, 20, T)
y <- rnorm(20) + x

df <- data.frame(x = ordered(x), y = y)

ggplot(df,aes(x,y)) + geom_point() + 
   scale_x_discrete(breaks = 1:5, labels = letters[1:5])

Solution 3 - R

Here is a reproducible example I think encapsulates your Q (?):

require(ggplot2)
dat <- data.frame(X = sample(1:5, 100, replace = TRUE),
                  Y = rnorm(100))

It isn't immediately clear what data you have, but if you mean something like this:

(p1 <- ggplot(dat, aes(x = X, y = Y)) + geom_point())

Then I think you want a stripchart, which can be achieved in ggplot via a factor

dat2 <- within(dat, X <- factor(X, labels = letters[1:5]))
(p2 <- ggplot(dat2, aes(x = X, y = Y)) + geom_point())

If this isn't what you mean, can you edit your Q to provide an example?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongappyView Question on Stackoverflow
Solution 1 - RChaseView Answer on Stackoverflow
Solution 2 - RPrasad ChalasaniView Answer on Stackoverflow
Solution 3 - RGavin SimpsonView Answer on Stackoverflow