Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - How to label the x-ticks using a column in my data.frame?

Tags:

r

ggplot2

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?

like image 645
Ping Tang Avatar asked Sep 06 '25 03:09

Ping Tang


2 Answers

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")

enter image description here

like image 113
Andrie Avatar answered Sep 07 '25 22:09

Andrie


Try this instead.

ggplot(data, aes(x = reorder(names, -rate), y = rate)) + 
    geom_bar(stat = "identity", fill = "grey")
like image 22
Teresa Ortiz Avatar answered Sep 07 '25 22:09

Teresa Ortiz