Hey Rony,
I think the reason that fct_reorder
isn't working is that you have repeated values in the partido
column, which may be causing the reordering to have problems. My general strategy for these types of things would be to define a vector that has the order that I want the values in partido
and then use factor(x, levels=order_vector)
to set the order before plotting the data. You can see this in my mutate
function call in the second code block below.
Your data is a little tricky because some of the values of partido
don't have a Sim
value in voto
. What I did to get it to work was to take df
and pivot_wider
, replacing the missing values with 0
and then use arrange
to order the parties by Sim and Nao. You could do Sim and the other category depending on what you wanted to do
sim <- df %>%
select(-n) %>%
pivot_wider(names_from="voto", values_from="perc", values_fill = 0) %>%
arrange(Sim, Nao)
Then sim$partido
would have the parties in the order you want them. So you can do the following to get the plot how you want it
df %>%
mutate(partido = factor(partido, levels = sim$partido)) %>%
ggplot(aes(y = partido, x = perc, fill = voto)) +
geom_bar(position = "fill", stat = "identity") +
geom_text(aes(label = perc),
position = position_fill(vjust = 0.5),
color = "white") +
theme_minimal()
Pat