Ggplot2, Geom_Bar, Dodge, Order of Bars

Changing the order of dodged bars in ggplot2 barplot

Hadley has provided a solution. Here's a replication of the problem and the solution.

The goal is to get the bars labeled "S" to come before the bars labeled "P". This doesn't happen by default because R orders levels alphabetically.

df <- read.csv("http://pealco.net/code/ggplot_dodge/df.txt")
ggplot(df, aes(gram, V1, fill=number))
+ geom_bar(stat="identity", position="dodge")

As Hadley commented in another answer, "you need to reorder based on the x variables, not the y variable". Though I'm not sure why this works.

To flip the order of the factors in this example, you can convert the factor to numeric and multiply by -1.

df <- with(df, df[order(gram, -as.numeric(number)), ])

I'd still like some more explanation about why df <- with(df, df[order(gram, -as.numeric(number)), ]) works.

ggplot2, geom_bar, dodge, order of bars

One option would be to make a new variable to represent the order the bars should be within each group and and add this variable as the group argument in your plot.

Lots of ways to that task of making the variable, here's a way using function from dplyr. The new variable is based on ranking ile in descending order within each klaster group. If you have ties in any group you'll want to figure out what you want to do in that case (what order should the bars be in given ties?). You may want to set the ties.method argument in rank away from the default, probably to "first" or "random".

library(dplyr)
ttt = ttt %>%
group_by(klaster) %>%
mutate(position = rank(-ile))
ttt
Source: local data frame [6 x 5]
Groups: klaster [2]

typ klaster ile rank position
(fctr) (fctr) (dbl) (dbl) (dbl)
1 main 1 5 3 3
2 boks 2 4 2 2
3 cuk 1 6 2 2
4 main 2 1 3 3
5 boks 1 8 1 1
6 cuk 2 7 1 1

Now just add group = position into your plot code.

ggplot() +
geom_bar(data=ttt, aes(x=klaster, y=ile, fill=typ, group = position),
stat="identity", color="black", position="dodge")

Sample Image

R - Issues with group order/ ggplot dodge barchart

To reorder the subsegment, assign factor to it and specify the orders in levels.

To reorder the bars within dodged bar chart, use reorder to order the dodged bars with descending size of values.

library(tidyverse)

ggplot(df, aes(factor(subsegment, levels = c("Sub3", "Sub1", "Sub2")),
values,
fill = reorder(company, desc(values)))) +
geom_bar(position="dodge", stat="identity", alpha=0.5) +
labs(x = "subsegment", fill = "company")

reorder_dodged_bar

how to specify the order of bar groups plotted with dodge position

You can either specify the xlimits:

desired = c('Soziale Medien', 'Lernen im Netz', 'Gratis Online Lernen 2014')

ggplot(AllCoursesReg, aes(Course, fill = Status)) +
geom_bar(position = "dodge", colour = "black") +
theme_bw()+
scale_x_discrete(limits=desired)+
guides(fill = guide_legend(reverse = TRUE))

Or change the levels of the factor:

AllCoursesReg$Course = factor(AllCoursesReg$Course,levels=desired)

ggplot(AllCoursesReg, aes(Course, fill = Status)) +
geom_bar(position = "dodge", colour = "black") +
theme_bw()+
guides(fill = guide_legend(reverse = TRUE))

Sample Image

Ordering position dodge in ggplot2

You have to decide on the ordering of the levels of a factor. Here's an example from ?geom_bar.

# example from ?geom_bar
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")
# reorder cut using levels = rev(levels(cut))
ggplot(diamonds, aes(clarity, fill=factor(cut, levels = rev(levels(cut))))) +
geom_bar(position="dodge") +
scale_fill_discrete('cut') # change name back to cut

Ordering bars in ggplot when dodged

You can set your factor levels like this :

occ_counts$Occupation <- with(occ_counts, factor(Occupation, 
levels = Occupation[Reportable == 'Report']
[order(-count[Reportable == 'Report'])]))

and then plot it as usual :

library(ggplot2)

ggplot(occ_counts, aes(fill=Reportable, y=count, x= Occupation, label = total1)) +
geom_bar(position="dodge", stat="identity")+
labs(x = "", y = "Injury Count", fill = "")+
lims(y = c(0,230)) +
geom_text(position = position_dodge(width = .9),
vjust = -0.5,
size = 3) +
scale_x_discrete(labels = function(x) stringr::str_wrap(x, 15))

Sample Image

ggplot2 - ordering dodge(d) columns

Here is a toy example that shows you how to re-order factors. In the first plot a comes first, in the second, z comes first.

df <- data.frame(b=1:10, c=c("z", "a"))
ggplot(df, aes(x=1, y=b, fill=c)) +
geom_bar(stat="identity", position="dodge")

df$c <- factor(df$c, levels=c("z", "a"))
ggplot(df, aes(x=1, y=b, fill=c)) +
geom_bar(stat="identity", position="dodge")

Reordering bar plots - R, ggplot, position = dodge

Why not include Type in your dataframe:

p <- rep(c("5e-8", "0.05", "1"), 2)
pgc1_rsq <- c(0.0037, 0.0726, 0.0847)
meta_rsq <- c(0.0263, 0.1829, 0.1753)
values <- c(pgc1_rsq, meta_rsq)
Type <- c(rep("PGC1", 3), rep("PGC meta-analysis", 3))
mydata <- data.frame(p, values,Type)
mydata$Type <- factor(mydata$Type, levels = c("PGC1","PGC meta-analysis"))
mydata$p <- factor(mydata$p, levels = c("5e-8", "0.05", "1"))

plot <-ggplot(mydata, aes(p, values))
plot +geom_bar(stat = "identity", aes(fill = Type), position = "dodge") + xlab("P-value threshold") + ylab("Proportion of variance explained (Nagelkerke Rsq)")

How to order a dodged bar chart?

Filter the data first for 'Party night', summarise the data and extract the city names in increasing order of Cost.

CostNightPrepared %>%
filter(Category == 'Party night') %>%
group_by(City) %>%
summarise(aveg = mean(Cost)) %>%
arrange(aveg) %>%
pull(City) -> lvls

Rearrange the factor levels, summarise the data and plot.

CostNightPrepared %>%
mutate(City = factor(City, lvls)) %>%
group_by(City, Category) %>%
summarise(Cost = mean(Cost)) %>%
ggplot(aes(Cost, City, fill=Category)) +
geom_bar(stat="identity",position = position_dodge(width = 0.5))

Sample Image



Related Topics



Leave a reply



Submit