简体   繁体   中英

How keep the order of categorical x on a histogram ggplot2 in R

I want to plot a histogram with categories on x and scores on y. The order from the table should be kept in the plot, but right now the plot gets reordered and the several posts on this I found on SO have not helped my case. for instance I tried this: Order Bars in ggplot2 bar graph

require(data.table)
require(ggplot2)

table <- structure(list(a = c(1, 2, 3, 4, 5, 6), b = c("grease", "surf", 
"lift", "zen", "ufo", "nothing"), c = c("3976.65457028497", "3700.27298336394", 
"3691.44157683915", "3687.89781035758", "3685.83200999925", "3685.44486138222"
)), .Names = c("a", "b", "c"), row.names = c(NA, -6L), class = c("data.table", 
"data.frame"))

ggplot(data=table) + geom_histogram(aes(x=b,y=c),stat='identity')

So this orders them in alphabetical order while I want them in decreasing c order. How would I do this?

From what I understood, this is what you are trying to do (I renamed your object table to table.dt):

ggplot(data=table.dt,aes(x=reorder(b,-as.numeric(c)),y=c)) +
  geom_histogram(stat='identity')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM