0

Good morning,

I'm trying to use ggplot with a data frame but I faced an issue. My ggplot doesn't take consideration about the function arrange on my data frame.

Here is my code :

data()
pop <- population[population$year == 1995, ]
pop <- pop[1:10, ] 

pop %>%
  ggplot(aes(x = country, y = population)) +
  geom_point()

pop <- pop %>%
  arrange(population)

pop %>%
  ggplot(aes(x = country, y = population)) +
  geom_point()

I would like that my graph would be arranged according to the population, so at the first place, the country with the lowest population, at the second place, the country with the second lowest population and so on. But ggplot doesn't match my graph as expected.

I have this data frame :

  country              year population
   <chr>               <int>      <int>
 1 Anguilla             1995       9807
 2 American Samoa       1995      52874
 3 Andorra              1995      63854
 4 Antigua and Barbuda  1995      68349
 5 Armenia              1995    3223173
 6 Albania              1995    3357858
 7 Angola               1995   12104952
 8 Afghanistan          1995   17586073
 9 Algeria              1995   29315463
10 Argentina            1995   34833168

But my graph is ordered by alphabetical order :

enter image description here

Do you have any idea to make it by population number?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Julien
  • 1
  • 1
  • 2
    You could try: `pop %>% ggplot(aes(x = reorder(country, population), y = population)) + geom_point()` – Quinten Jan 16 '23 at 17:22
  • @Quinten Thanks for your answer. In fact, do I need to do my arrange (other function effect) inside ggplot rather than in another part? – Julien Jan 16 '23 at 17:57
  • In R, categories stored as character (see `` in your data frame example) will be sorted in alphabetical order, and ggplot2 respects this. To give them a different order, you typically would make them into a "factor," in this case ordered by population. This can be done in your original data set, or inline in your ggplot code like in Quinten's example. – Jon Spring Jan 16 '23 at 19:29

0 Answers0