user5359735
user5359735

Reputation:

Reordering columns by y-value in R?

I have a dataframe structured like this:

> head(df)
    Zip Crimes Population    CPC
1 78701   2103       6841 0.3074
2 78719    186       1764 0.1054
3 78702   1668      21334 0.0782
4 78723   2124      28330 0.0750
5 78753   3472      49301 0.0704
6 78741   2973      44935 0.0662

And I'm plotting it using this function:

p = ggplot(df, aes(x=Zip, y=CPC)) + geom_col() + theme(axis.text.x = element_text(angle = 90))

And this is the graph I get:

p

How can I order the plot by CPC, where the highest Zip codes are on the left?

Upvotes: 0

Views: 3333

Answers (2)

jvb
jvb

Reputation: 61

Sort your data frame in descending order and then plot it:

library(dplyr)
df <- arrange(df,desc(CPC))
ggplot...

Upvotes: 0

Simon Jackson
Simon Jackson

Reputation: 3184

Convert Zip to a factor ordered by negative CPC. E.g., try df$Zip <- reorder(df$Zip, -df$CPC) before plotting. Here's a small example:

d <- data.frame(
  x = c('a', 'b', 'c'),
  y = c(5, 15, 10)
)

library(ggplot2)

# Without reordering
ggplot(d, aes(x, y)) + geom_col()

enter image description here

# With reordering
d$x <- reorder(d$x, -d$y)
ggplot(d, aes(x, y)) + geom_col()

enter image description here

Upvotes: 1

Related Questions