Why ggplot change the order of the variables by default? and how to solved it.

I don't know why ggplot change the order of the variables of a data frame.
I want to plot first "Línea 1", then "Línea 2", then "Línea 3" and so on... following the order of the data frame.
But ggplot changes the order :confused:

How can I solved it?
Here is the code to create the graph:

ggplot(p3_tab1_2, aes(fill=tipo_trenes, y=trenes, x=lineas)) + 
  geom_bar(position="stack", stat="identity") +
  geom_text(aes(label = trenes, group =tipo_trenes), color = "white",position = position_stack(vjust = .5)) +
  scale_fill_manual(values = c("green3", "red")) +
  theme_minimal() + ylab(" ") + xlab(" ") + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        legend.position = "bottom",
        axis.text=element_text(size=15),
        legend.text = element_text(size=15)) + 
  labs(fill = " ") +
  geom_text(aes(lineas, total, label = total, fill = NULL), data = trenes_totales,position = position_stack(vjust = 1)) 

It converts the categorical variable to a factor. The factor is by default alphabetical.

Does this tutorial help?

If your data is already ordered as you want, you can use forcats::fct_inorder()

ggplot(p3_tab1_2, aes(fill=tipo_trenes, y=trenes, x=fct_inorder(lineas))) +
....

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.