mfk534
mfk534

Reputation: 719

Rearranging Numeric Axis

I'm trying to plot data and running into an issue with a numeric axis. It should be plotted in order:

1, 2, 3, 4, 5... 22, X, Y

Instead it's plotting like this:

1, 10, 11, 12... 2, 22, 3, 4..., X, Y 

I've tried changing the column in question with as.character, as.factor, as.numeric. I've also checked out a few "rearrange" suggestions, but they all deal with the observations themselves, and not the axis.

What am I overlooking?

Here is a sample of the data:

Chr Chunk   A   B   C
1   1   3   4   4
1   2   3   4   4
1   3   3   2   4
1   4   3   4   9
2   1   3   3   4
2   2   3   4   4
2   3   3   4   4
10  1   3   4   4
10  2   3   4   4
X   1   3   4   5
X   2   3   4   8
Y   1   3   4   5

I'm attempting to make a series of heat plots using ggplot:

heat <- ggplot(data, aes(Chr, Chunk, fill = A, label = sprintf("", A))) +  geom_tile() + geom_text() + scale_fill_gradient2(high = "red")

Upvotes: 1

Views: 54

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

Since you’re dealing with character data, ggplot will simply sort your data for plotting (and character strings are lexicographically ordered, such that '10' comes before '2'). If you want to influence the order, convert your character to an ordered factor. Unfortunately this requires actually providing the order manually (but in your case that order isn’t too hard to write down):

data$Chr = factor(data$Chr, levels = c(1 : 22, 'X', 'Y'), ordered = TRUE)

Upvotes: 2

Related Questions