Ordering Bars in Barplot()

Re-ordering bars in R's barplot()

I get the following,

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:10])
data <- data.frame(num, cat)
barplot(data[order(data[,1],decreasing=TRUE),][,1],names.arg=data[order(data[,1],decreasing=TRUE),][,2])

The above code uses the order() function twice (see comments, below). To avoid doing this the results of the ordered data.frame can be stored in a new data.frame and this can be used to generate the barplot.

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:10])
data <- data.frame(num, cat)
data2 <- data[order(data[,1],decreasing=TRUE),]
barplot(data2[,1],names.arg=data2[,2])

How to order the bars in a seaborn barplot

You can just use the original df and specify the ordering with barplot's order param.

  1. The order can be determined by sorting the output of groupby.mean:

    order = df.groupby('job_title').mean().sort_values('salary_in_usd').index
  2. Then use this order along with data=df:

    sns.barplot(
    x='job_title',
    y='salary_in_usd',
    data=df,
    order=order,
    ci=None,
    )

Order Bars in ggplot2 bar graph

The key with ordering is to set the levels of the factor in the order you want. An ordered factor is not required; the extra information in an ordered factor isn't necessary and if these data are being used in any statistical model, the wrong parametrisation might result — polynomial contrasts aren't right for nominal data such as this.

## set the levels in order we want
theTable <- within(theTable,
Position <- factor(Position,
levels=names(sort(table(Position),
decreasing=TRUE))))
## plot
ggplot(theTable,aes(x=Position))+geom_bar(binwidth=1)

barplot figure

In the most general sense, we simply need to set the factor levels to be in the desired order. If left unspecified, the levels of a factor will be sorted alphabetically. You can also specify the level order within the call to factor as above, and other ways are possible as well.

theTable$Position <- factor(theTable$Position, levels = c(...))

Change order of bars in Barplot

Before you plot, change your uitleg as follows:

etadam$uitleg <- factor(etadam$uitleg, levels = c('Kan beter', 'Normaal', 'Goed', 'Zeer goed'))

Then, ggplot() will use the levels in that order on the x-axis.

Sorting bars of a barplot

Try this aes in your ggplot

aes(fill=combinedwith.tx, x=reorder(treatment.tx, dateorder), y=mean_hatch)

where dateorder is a new numeric variable in the order you like to display the bars.

Ordering bars in barplot()

As stated by Henrik, you need to get your data into a factor (at least this is the easiest easiest way to make this happen). Consider the following example with some fake data...

#generate 1000 random uniform integers between 1 and 5
data <- floor(runif(1000, 1,6))

#make data a factor with given labels
fdata <- factor(data,
labels = c("No use",
"30 min",
"1 hour",
"2 hours",
"3+ hours"))

This can be done in base r with plot (barplot is not required when y is not specified)

#in base R, just use plot - when y is missing, barplot is produced
plot(fdata)

You can also plot in ggplot2

#in ggplot2
require(ggplot2)

#make a dataframe
df <- data.frame(id = seq(1:length(fdata)),
fdata = fdata)

#plot via geom_bar
ggplot(df, aes(fdata)) + geom_bar()

Proceeding from your original example, in addition to specifying levels, you are going to need to set ordered=TRUE as shown below. Otherwise, "No use" will still show up at the end of your list.

#get data into a factor (provided data plus "No use")
q1 <- c("No use"
,"1 hour"
,"1 hour"
,"30 min"
,"2 hours"
,"3+ hours"
,"3+ hours"
,"3+ hours"
,"3+ hours"
,"2 hours"
,"1 hour"
,"2 hours"
,"1 hour"
,"30 min")

q1f = factor(q1,
levels = c("No use",
"30 min",
"1 hour",
"2 hours",
"3+ hours"),
ordered=TRUE)

Then you can apply the plot logic shown above...

How to plot a bar plot by ggplot2 and sort bars in non-alphabetical order

We could use fct_relevel from forcats package (it is in tidyverse).

  1. Bring your rownames to a column gene with rownames_to_column function from tibble package (it is in tidyverse)

  2. Use fct_relevel to set the order as you wish

  3. Then use ggplot2 (I used geom_col())

library(tidyverse)

mydata %>%
rownames_to_column("gene") %>%
pivot_longer(
cols = -gene
) %>%
mutate(gene = fct_relevel(gene,
"SHO", "DRG", "ALA", "XPA")) %>%
ggplot(aes(x=gene, y=value))+
geom_col(color="green" , fill="yellowgreen", position="dodge" , width = 0.5)+
xlab("Genes")+
ylab("Expression") +
theme(axis.text.x = element_text(size = 10, angle = 45, hjust = 1),
plot.margin = margin(0.5,0.5,0.5,2, "cm"))

Sample Image

Seaborn Bar Plot Ordering

You have to sort your dataframe in desired way and the reindex it to make new ascending / descending index. After that you may plot bar graph with index as x values. Then set set labels by Dim column of your dataframe:

import matplotlib.pylab as plt
import pandas as pd
import seaborn as sns

dicti=({'37':99943,'25':47228,'36':16933,'40':14996,'35':11791,'34':8030,'24' : 6319 ,'2' :5055 ,'39' :4758 ,'38' :4611 })
pd_df = pd.DataFrame(list(dicti.items()))
pd_df.columns =["Dim","Count"]
print (pd_df)
# sort df by Count column
pd_df = pd_df.sort_values(['Count']).reset_index(drop=True)
print (pd_df)

plt.figure(figsize=(12,8))
# plot barh chart with index as x values
ax = sns.barplot(pd_df.index, pd_df.Count)
ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: "{:,}".format(int(x))))
ax.set(xlabel="Dim", ylabel='Count')
# add proper Dim values as x labels
ax.set_xticklabels(pd_df.Dim)
for item in ax.get_xticklabels(): item.set_rotation(90)
for i, v in enumerate(pd_df["Count"].iteritems()):
ax.text(i ,v[1], "{:,}".format(v[1]), color='m', va ='bottom', rotation=45)
plt.tight_layout()
plt.show()

Sample Image



Related Topics



Leave a reply



Submit