0

I have a small dataset that looks like this:

Name<-c("Al","Al","Ellen","Ellen","Luisa","Luisa","Mark","Mark","Randy","Randy")
Sex<-c("M","F","M","F","M","F","M","F","M","F")
Value<-c(0,1,2,3,6,4,7,3,5,1)
mydata<-data.frame(Name,Sex,Value)

I would like to have a plot like this one:

p<-ggplot(mydata, 
          aes(x=reorder(Name,-Value), 
              y=Value,
              fill=Sex)) + 
  geom_bar(stat = "identity",
           position="stack") +
  scale_fill_manual(values=c("#3CBB75FF","#95D840FF")) + 
  xlab("Name") + 
  ylab("Value") + 
  scale_y_continuous(limits = c(0, 10), 
                     breaks = seq(0, 10, by = 2)) +
  theme(axis.line = element_blank(),
        axis.text.x=element_text(angle = 90,
                                 vjust = 0.35,
                                 hjust=1,
                                 size=13,
                                 face="italic",
                                 margin=margin(b=10),
                                 colour="black"),
        axis.text.y=element_text(size=13,
                                 margin=margin(l=10),
                                 colour="black"),
        axis.ticks = element_blank(), 
        axis.title=element_text(size=18,
                                face="bold"),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), 
        panel.background = element_blank(),
        legend.text = element_text(size=14),
        legend.title = element_blank()) 
p

I would like to have the names ordered by the highest value of M. Is there a way to maintain the alphabetical order when M is equal (as in the case of Al and Randy) but having as first the highest value of M when the sum M+F is equal (as in the case of Luisa and Mark)? I would like Mark before Luisa. Any suggestions?

LT17
  • 227
  • 1
  • 8
  • 2
    Just about every [tag:ggplot2] question on SO that asks about order on an axis or facet is resolved by converting the respective variable to a `factor` and explicitly controlling the order with `factor(., levels=)`. – r2evans Apr 16 '21 at 17:54
  • *"when M is equal (as in the case of Al and Randy"* ... Al and Randy are completely different, both as individual values and their sum. – r2evans Apr 16 '21 at 17:59

1 Answers1

0
mydata$Value2 <- ave(mydata$Value, mydata$Name, FUN = sum)
with(subset(mydata, Sex == "M"), Name[order(-Value2, -Value, Name)])
# [1] "Mark"  "Luisa" "Randy" "Ellen" "Al"   
mydata$Name <- factor(mydata$Name, levels = with(subset(mydata, Sex == "M"), Name[order(-Value2, -Value, Name)]))
str(mydata)
# 'data.frame': 10 obs. of  4 variables:
#  $ Name  : Factor w/ 5 levels "Mark","Luisa",..: 5 5 4 4 2 2 1 1 3 3
#  $ Sex   : chr  "M" "F" "M" "F" ...
#  $ Value : num  0 1 2 3 6 4 7 3 5 1
#  $ Value2: num  1 1 5 5 10 10 10 10 6 6

enter image description here

r2evans
  • 141,215
  • 6
  • 77
  • 149