drbunsen
drbunsen

Reputation: 10709

Reorder axis values to ascending values with ggplot2?

I'm trying to produce a simple ggplot2 jitter plot in R. For x values, I have integers between 1 and 100. When I plot this data my x axis start with a value of 1 then goes to 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, etc. How can I reorder my x axis to create ascending values (eg. 1, 2, 3, 4, 5, ... etc.)?

Here is my code:

data = read.csv('my_data_file', sep"\t")
x_values = data[,1]
y_values = data[,2]  
qplot(rank, score, geom="jitter")  

EDIT: I should have pointed out that I also have a few non-integer x values. Ideally, I would like the x axis to ascend by number and then have the non-integer values appended to the end of the x axis. Any order for the non-integer values is fine.

Upvotes: 1

Views: 2107

Answers (2)

Ari B. Friedman
Ari B. Friedman

Reputation: 72769

Your x variable had quotes around it in the CSV (Excel is notorious for this), which means that R read it in as a factor, which it alphabetizes the levels by default. Fix the levels and you'll fix the ordering. Or better yet, since x seems to naturally want to be an integer, fix your data type:

x_values <- as.integer(as.character(x_values))

Try str(data) to see the data types of your columns. If your data is big there are more efficient ways to convert.

Upvotes: 1

ROLO
ROLO

Reputation: 4223

You have to convert to numeric, as @gsk3 says, but as this answer points out, there are some difficulties, and you should use:

x_values <- as.numeric(levels(x_values))[x_values]

Upvotes: 3

Related Questions