r - Use reorder in ggplot2 wrapped in a function -


background

i building function wrap ggplot2 follow:

df <- data.frame("variable" = c("chk_account3", "amount", "duration"), "overall_imp" = c(71.44, 54.24, 34.84))      clevelandplot <- function (dataframe, xvalue, yvalue) {    ggplot(data = dataframe, aes_string(x=xvalue, y=yvalue)) +     geom_segment(aes_string(yend = yvalue), xend = 0, colour = "grey50") +     geom_point(size=3) +     scale_x_continuous(expand = c(0.01, 0)) +     theme_bw() +     theme(panel.grid.major.y = element_blank()) +     xlab("importance") +     ylab("")  } 

this function works:

clevelandplot(df, "overall_imp", "variable") 

enter image description here

but when try reorder values following code, not work:

clevelandplot <- function (dataframe, xvalue, yvalue) {    ggplot(data = dataframe, aes_string(x=xvalue, y=reorder(yvalue, xvalue))) +     geom_segment(aes_string(yend = yvalue), xend = 0, colour = "grey50") +     geom_point(size=3) +     scale_x_continuous(expand = c(0.01, 0)) +     theme_bw() +     theme(panel.grid.major.y = element_blank()) +     xlab("importance") +     ylab("")  } 

question

how reorder variable in y axis in decreasing order (biggest value @ top of plot)?

clevelandplot <- function (dataframe, xvalue, yvalue) {    ix <- sort.int(dataframe[,xvalue], decreasing = false, index.return = true)$ix   dataframe[,yvalue] <- factor(dataframe[,yvalue], dataframe[ix,yvalue])    ggplot(data = dataframe, aes_string(x=xvalue, y=yvalue)) +     geom_segment(aes_string(yend = yvalue), xend = 0, colour = "grey50") +     geom_point(size=3) +     scale_x_continuous(expand = c(0.01, 0)) +     theme_bw() +     theme(panel.grid.major.y = element_blank()) +     xlab("importance") +     ylab("") }  clevelandplot(df, "overall_imp", "variable") 

enter image description here


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -