How to put Y-axis variables in ascending order in ggplot

Asked

Viewed 298 times

-1

I had to rename the Y variables of a ggplot, but I need them to be in ascending order so that the data correctly track its variables. I need you to start with #MB02


myc_t
DateTime    Receiver    Transmitter ID  Transmitter.Serial  Sensor.Value Sensor.Unit    Station Name    Longitude   Latitude
2019-04-29  05:31:33    134321  4828    Fran    1305297         28.7       °C             PRN               102          121
2019-04-29  08:52:08    134325  4830    Beni    1305283         4.2         m             MVW               102          178
2019-04-29  08:53:13    134325  4831    Silvo   1305283         28.6       °C             MVW               150          178


ggplot(myc_t,aes(x=DateTime,y=Transmitter)) +  geom_point(stat="identity") +
  labs(x = "Período de monitoramento acústico", y = "Frequência de detecção")+ scale_y_discrete(labels = c("#MB04", "#MB05","#MB06","#MB07","#MB08","#MB03","#MB09","#MB10", "#MB11", "#MB12", "#MB02", "#MB13", "#MB14", "#MB15", "#MB16"))




  • 2

    Hi Franciele, you can pass your data with dput() the way this is difficult to answer, but probably you will use something with aes(x = DateTime,y = fct_reorder(Transmitter,alguma_coluna)

  • See the guide on how to ask a good question here and here

2 answers

0

Inside the data.frame, before transforming it into a ggplot object, classify this variable using the Sort function, which will place it in alphabetical order.

Example:

dados = dados[sort(dados$variavel),]

If this variable is not already in your data.frame, you can add it based on some column.

Example: I want to create a column based on another column with a new category. Let’s say I want to put in the new column "GEOCOD", the number "53" for the lines whose state is "DF".

dados$GEOCOD[dados$UF == "DF"]= "53"

0

Hello, first of all, use the "reorder" function within the y parameter. I will also take the opportunity to suggest a better way of organizing your code, to facilitate even your understanding and others who need to work with you, okay? Thus:

ggplot(data = myc_t,
       aes(x = DateTime,
           y = reorder(Transmitter, -DateTime))) +
       geom_point(stat = "identity") +
       labs(x = "Período de monitoramento acústico",
            y = "Frequência de detecção")+ 
       scale_y_discrete(labels = c("#MB04", "#MB05","#MB06","#MB07","#MB08","#MB03","#MB09","#MB10", "#MB11", "#MB12", "#MB02", "#MB13", "#MB14", "#MB15", "#MB16"))

The "reorder" function will organize the values of "y" in ascending order, if you want in descending order, use the "+" instead of the "-". If you want "x" to be organized this way, instead of "y", just take the reorder function of "y" and put it in "x".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.