[R] ggplot2 geom_bar arrangement

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Wed Jun 28 10:40:34 CEST 2017


In the general case it is not possible to do as you ask because "Lab" can be duplicated. However, in your specific case it is unique in your data frame, so you just have to control the order of the factor labels instead of letting them be set up in the default manner. Of course, you have to be aware that sticking character vectors into data frames without using the stringsAsFactors argument (read the help on the data.frame function) means they get converted to factors automatically so that is where you have to take control. 

df <- data.frame( Lab=factor( Lab, labels=Lab ),valuex)
-- 
Sent from my phone. Please excuse my brevity.

On June 27, 2017 2:43:34 PM EDT, Brian Smith <bsmith030465 at gmail.com> wrote:
>Hi,
>
>I was trying to draw a geom_bar plot. However, by default, the bars are
>arranged according to the label, which I don't want. I want the bars to
>appear exactly as they appear in the data frame. For example in the
>code:
>
> Lab=c(letters[4:6],letters[1:3])
> valuex = c(3.1,2.3,0.4,-0.4,-1.2,-4.4)
> df <- data.frame(Lab,valuex)
> px <- ggplot(df,aes(Lab,valuex,label=Lab)) + geom_text(aes(y=0)) +
>geom_bar(stat = "identity")
> px
>
>
>The default arranges the bars in order 'a' through 'f', but I want them
>arranged as per df.
>
>How can I do this?
>
>thanks!
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list