Order and Color of Bars in Ggplot2 Barplot

Order and color of bars in ggplot2 barplot

The order that bars are drawn (bottom to top) in a stacked barplot in ggplot2 is based on the ordering of the factor which defines the groups. So the Biogeographic.affinity factor must be reordered. Generally we use reorder(if we want to order the factor according to a continuous levels) but here I will just create a new ordered factor similar to what you tried to do.

 biogeo <- transform(biogeo, 
Biog.aff.ord = factor(
Biogeographic.affinity ,
levels=c( 'Bassian','Widespread','Torresian', 'Eyrean'),
ordered =TRUE))

Now if you fill your barplot using Biog.aff.ord rather than the original factor and overriding the default grouping order by defining aes_group_order as Biog.aff.ord order you get the expected result:

cols <- c(Bassian="darkgrey",Widespread="lightgrey", 
Torresian="white", Eyrean="black")
ggplot(data=biogeo, aes(x=Site, y=Percent,
order=Biog.aff.ord)) + ##!! aes_group_order
geom_bar(stat="identity", colour="black",
aes(fill=Biog.aff.ord)) +
scale_fill_manual(values = cols)

Sample Image

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(...))

Bar plot in ggplot2 with ordered bars and manually specified colours

With scale_fill_manual you assign colors to levels in your data.
At the same time, you use reorder(shop, revenue) in the definition of aes, which orders the data from left to right in ascending order. The third and last definition of the color "blue" was assigned to c which is now at the left hand side as it is the smallest.

You could time this to circumvent this:

ggplot(data = df, aes(x = reorder(shop, revenue), y = revenue, fill = shop)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("yellow", "black", "blue")) + # CHANGED
theme_minimal()

Or as @JeroenBoeye suggested:

ggplot(data = df, aes(x = reorder(shop, revenue), y = revenue, fill = shop)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("c" = "blue", "a" = "yellow", "b" = "black")) + # Jeroen Boeye's suggestion
theme_minimal()

Please let me know whether this solves your problem.

Plotting Bar Chart in custom order and color sequence using ggplot library in R

I figured out the issues and have posted my answer inspired by @cymon's and @Ronak Shah's solutions.

library(ggplot2)

z <- data.frame(group = c("trtA", "trtAB", "trtB", "veh"),
Mean = c(42.990, 50.955, 34.235, 31.992),
sd = c(15.541, 18.325, 9.737, 12.463))

colorVals = c("black", "red", "blue", "purple")

# Before assigning new values to existing 'group' values

ggplot(z, aes(x=group, y=Mean, fill = group )) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=Mean-sd, ymax=Mean+sd), width=.4) +
geom_text(aes(label=round(Mean,2), fontface = "bold"), vjust = -0.5) +
scale_fill_manual(values=colorVals) +
labs(x = "Treatment Group", y = "Signal Value") +
theme_classic(base_size = 14) +
theme(legend.position='none') +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
scale_fill_manual("legend", values = colorVals)

# After assigning new values to existing 'group' values

GroupA <- "Vehicle"
GroupB <- "Treatment-A"
GroupC <- "Treatment-B"
GroupD <- "Treatment-AB"

names(colorVals) <- c(GroupA, GroupB, GroupC, GroupD)

z$group[z$group == "veh"] <- GroupA
z$group[z$group == "trtA"] <- GroupB
z$group[z$group == "trtB"] <- GroupC
z$group[z$group == "trtAB"] <- GroupD

z$group <- factor(z$group, ordered=TRUE, levels=names(colorVals))

ggplot(z, aes(x=group, y=Mean, fill = group )) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=Mean-sd, ymax=Mean+sd), width=.4) +
geom_text(aes(label=round(Mean,2), fontface = "bold"), vjust = -0.5) +
scale_fill_manual(values=colorVals) +
labs(x = "Treatment Group", y = "Signal Value") +
theme_classic(base_size = 14) +
theme(legend.position='none') +
theme(axis.text.x = element_text(angle = 20, hjust = 1)) +
scale_fill_manual("legend", values = colorVals)

In ggplot2 bar chart legend elements in wrong order and one player's bar colors are off

Try this

win_dfL %>%
ggplot(aes(x=Pitcher, y=Wins, fill=Season)) +
geom_bar(stat="identity", color="black", width = .85, position = position_stack(reverse = TRUE)) +
scale_fill_manual(values=c("#A0522D",
"#FAD5A5",
"red",
"white",
"gray",
"#C04000",
"#FF7518",
"yellow")) +
# Horizontal bar plot
coord_flip() +
guides(fill = guide_legend(override.aes = list(color = NA)))

Sample Image

position = position_stack(reverse = TRUE) within geom_bar reverses the color sequence, and guides(fill = guide_legend(override.aes = list(color = NA))) gets rid of the borders in the legend.

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

Sample Image

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)

Sample Image

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

Sample Image

How do you order the fill-colours within ggplot2 geom_bar

You need to specify the order aesthetic as well.

ggplot(data,aes(mon,NG,fill=gclass,order=gclass))+
geom_bar(stat="identity")

Sample Image

This may or may not be a bug.

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



Related Topics



Leave a reply



Submit