0

I have a df that seems like this:

    CIUDAD    MPond_Ciud IDPROV MPond_Prov   PCPROV     DIFMP
1     ABANCAY   513.2121    301   490.4090 72.28465  22.80311
2 ANDAHUAYLAS   382.7516    302   318.6479 57.21274  64.10372
3    AREQUIPA   703.0134    401   683.6721 93.61579  19.34131
4    AYACUCHO   461.3796    501   387.6766 79.26356  73.70302
5     AYAVIRI   404.8749   2108   253.2098 36.42051 151.66505
6    AZANGARO   289.3249   2102   183.8901 27.23929 105.43477

##DIFMP is the result of MPond_Ciud - MPond_Prov

What I am looking for is to obtain a graph that allows visualizing the distance between MPond_Ciud and MPond_Prov. For that I use this code

ggplot(df) +
  geom_segment( aes(x=CIUDAD, xend=CIUDAD, y=MPond_Prov, yend=MPond_Ciud), color="grey") +
  geom_point( aes(x=CIUDAD, y=MPond_Prov), color=rgb(0.2,0.7,0.1,0.5), size=3 ) +
  geom_point( aes(x=CIUDAD, y=MPond_Ciud), color=rgb(0.7,0.2,0.1,0.5), size=3 ) +
  coord_flip()+
  theme(
    legend.position = "none",
  ) +
  xlab("") +
  ylab("")

which returns this graph:

enter image description here

In principle it is not bad, but if you notice the Y axis is ordered alphabetically. What I want is to reorder it from highest to lowest values of column DIFMP.

Is there a way to do so?

José Rojas
  • 313
  • 1
  • 8
  • 1
    I think every question (or at least the vast majority) that include `ggplot2` and "order of " is answered by converting the specific variable to `factor` and controlling the order yourself with `levels=`. – r2evans Jul 14 '21 at 00:19

1 Answers1

0

Original image:

alphabetic order

df$CIUDAD <- factor(df$CIUDAD, levels=unique(df$CIUDAD[order(df$DIFMP)]))
df[order(df$DIFMP),]
#        CIUDAD MPond_Ciud IDPROV MPond_Prov PCPROV  DIFMP
# 3    AREQUIPA      703.0    401      683.7  93.62  19.34
# 1     ABANCAY      513.2    301      490.4  72.28  22.80
# 2 ANDAHUAYLAS      382.8    302      318.6  57.21  64.10
# 4    AYACUCHO      461.4    501      387.7  79.26  73.70
# 6    AZANGARO      289.3   2102      183.9  27.24 105.43
# 5     AYAVIRI      404.9   2108      253.2  36.42 151.67

Newly ordered image:

fixed order using factors

r2evans
  • 141,215
  • 6
  • 77
  • 149