Reputation: 425
Here is my data.frame:
names order rate chance_level
Neutral 1 77% 0.076923077
Blaming 2 66% 0.076923077
Insincere 3 61% 0.076923077
Polite 4 59% 0.076923077
Commanding 5 58% 0.076923077
Prasing 6 57% 0.076923077
Friendly 7 48% 0.076923077
Sincere 8 46% 0.076923077
Joking 9 39% 0.076923077
Hostile 10 39% 0.076923077
Rude 11 36% 0.076923077
Serious 12 33% 0.076923077
Suggestion 13 16% 0.076923077
Here is my code:
ggplot(data = data, aes(x = order)) +
geom_bar(aes(y = rate), stat = "identity", fill = "grey") +
scale_x_continuous(breaks = c(1:13),
labels = c("Reluctant","Joking","Suggestion","Blaming", "Neutral","Seriously","Command","Prasing", "Frankly","Friendly","Polite","Hostile", "Rude"))
So, as you see, I have to manually type in the tick-labels of x-axis in the correct order, so, how can I get add ticks-labels with correctly order using the column "names" rather than this idiot way?
Upvotes: 4
Views: 6239
Reputation: 11
Try this instead.
ggplot(data, aes(x = reorder(names, -rate), y = rate)) +
geom_bar(stat = "identity", fill = "grey")
Upvotes: 1
Reputation: 13300
First, make rate numeric, otherwise it is not represent on a appropriate scale.
Then you can reorder the x-axis easily via reorder():
df <- read.table(header = TRUE, text = 'names order rate chance_level
Neutral 1 77% 0.076923077
Blaming 2 66% 0.076923077
Insincere 3 61% 0.076923077
Polite 4 59% 0.076923077
Commanding 5 58% 0.076923077
Prasing 6 57% 0.076923077
Friendly 7 48% 0.076923077
Sincere 8 46% 0.076923077
Joking 9 39% 0.076923077
Hostile 10 39% 0.076923077
Rude 11 36% 0.076923077
Serious 12 33% 0.076923077
Suggestion 13 16% 0.076923077')
df$rate <- as.numeric(gsub('%', '', df$rate))
require(ggplot2)
ggplot() +
geom_bar(data =df, aes(x = reorder(names, order), y = rate), stat = "identity", fill = "grey")
Upvotes: 0
Reputation: 179468
The trick is to turn your column names
into a factor, with level order determined by order
.
You can use the function reorder()
to do this:
dat$names <- reorder(dat$names, dat$order)
Then plot:
ggplot(data = dat, aes(x = names, y = rate)) +
geom_bar(stat = "identity", fill="grey")
Upvotes: 3