I have a data frame that looks like this:
data <- structure(list(Sex = c("Male", "Male", "Male", "Male", "Female",
"Male", "Female", "Female", "Female", "Female", "Male", "Female",
"Female", "Female", "Male"), Nationality = c("USA", "USA", "USA",
"UK", "UK", "UK", "France", "France", "France", "France", "France",
"USA", "Canada", "Canada", "Mexico")), row.names = c(NA, 15L), class = "data.frame")
And I've plotted it like that:
ggplot(data, aes(x = factor(Nationality))) +
geom_bar(aes(y = (..count..)/sum(..count..), fill = Sex), width = 0.3) +
scale_y_continuous(labels = percent, limits = c(0, 0.4))+
coord_flip()
I want to do 2 things:
(1) Re-order the bars in descending order, so that the first bar is the one with the highest count. I have tried reorder
as found in other questions on stackoverflow, but I couldn't make it work. Is it because I am using percentages? Please note that I do NOT want to use the sum of counts in the graph, as I still want to be able to represent sex in the plot (i.e., data must not be collapsed). I believe that this particular issue has not been replied before.
(2) Add a label with the count value inside each bar. I have tried the following, but it did not work. The problem is that I don't know how to refer to counts in this context.
geom_text(aes(label = Nationality), nudge_y = +1)
Note. To CLARIFY what I meant by not collapsing data: I know that I could mutate and create a new dataframe with the sums of counts for each nationality. But then I would lose the counts for each sex (the data will be collapsed), and therefore I could no longer represent sex in the plot.
reorder
answer should work just fine, and you'll have acount
column with no confusion of how to refer to it. – Gregor Thomas