Napier
Napier

Reputation: 227

order count in ggplot

This is my code

ggplot(apartment,
       aes(x=AnnualPrice,
           y=Region,
           color=Region))+
  labs(title = "The Annual Price of Apartments in Different Regions",
       subtitle="Jabodetabek Region",
       x="Annual Price",
       y="Region")+
  geom_jitter(size=1.5)+
  scale_x_continuous(labels = scales::unit_format(prefix = "Rp",unit = ""))+
  theme_minimal()+
  theme(plot.title = element_text(hjust=.5),
        plot.subtitle = element_text(hjust=.5),
        axis.title = element_text(size=15),
        legend.position = "none")

and this is the result

enter image description here

but i want reordered it by region count. I've tried this code, but it gives me an error

ggplot(apartment,
           aes(x=AnnualPrice,
               y=reorder(Region,count),
               color=Region))+
      labs(title = "The Annual Price of Apartments in Different Regions",
           subtitle="Jabodetabek Region",
           x="Annual Price",
           y="Region")+
      geom_jitter(size=1.5)+
      scale_x_continuous(labels = scales::unit_format(prefix = "Rp",unit = ""))+
      theme_minimal()+
      theme(plot.title = element_text(hjust=.5),
            plot.subtitle = element_text(hjust=.5),
            axis.title = element_text(size=15),
            legend.position = "none")

any suggestions ???

Upvotes: 0

Views: 25

Answers (1)

r2evans
r2evans

Reputation: 160447

Just about every issue with ggplot2 that starts with "order of ..." is resolved with factor and levels.

mt <- mtcars
mt$cyl <- factor(mt$cyl)
levels(mt$cyl)
# [1] "4" "6" "8"
library(ggplot2)
ggplot(mt, aes(mpg, cyl, color = cyl)) + geom_jitter(size=3, height=0.1)

ggplot2 with categorical variable unordered

mt <- mtcars
mt$cyl <- factor(mt$cyl, levels = names(sort(table(mt$cyl), descending=TRUE)))
levels(mt$cyl)
# [1] "6" "4" "8"
ggplot(mt, aes(mpg, cyl, color = cyl)) + geom_jitter(size=3, height=0.1)

ggplot2 with categorical variable ordered by size

Upvotes: 1

Related Questions