# Barplot without alphabetizing x-axis

I'm inputting a .csv file and then plotting a barplot based on the colnames but when I go plot the order the names are being alphabetized rather than get the order that is in the .csv file. How to I prevent that from happening?

p2 = ggplot(data=clusters_per_sample, aes(x=sample, y=Perc, fill=cluster)) +
geom_bar(stat="identity")+
scale_fill_manual(values = getPalette(22))+
theme_minimal() + labs(y="percentage of total # cells in the sample") + theme(axis.text.x = element_text(angle = 90, face = "bold")) + theme(axis.text.x = element_text(size=12, color="black"))


I tried this to get rid of the alphabetizing but my bars are very thin when doing so:

p2 = ggplot(data=clusters_per_sample_2, aes(x=sample, y=Perc, fill=cluster)) +
geom_bar(stat="identity")+ scale_x_discrete(limits=clusters_per_sample_2$sample) + heme_minimal() + labs(y="percentage of total # cells in the sample") + theme(axis.text.x = element_text(angle = 90, face = "bold")) + theme(axis.text.x = element_text(size=12, color="black"))  Any suggestions? ## 1 Answer ggplot2 uses factors on the underlying data frame. To have the data plotted in a custom order, apply a custom ordered factor on the underlying dataset. For example, if clusters_per_sample$sample is your custom-ordered vector, do this:

clusters_per_sample$$sample <- factor(clusters_per_sample$$sample, levels = unique(clusters_per_sample\$sample), ordered = TRUE)


Now when you plot sample as an aesthetic, ggplot has a factor component to work with already, so it won't try and make a new one (this new factor would have been in alphabetical order, which we circumvent with the ordered=TRUE parameter in our custom factor).

• Where do I add that line in my code?
– mmpp
Aug 18 '21 at 17:25
• Add it in before passing the object to ggplot(). This step is part of preparing your data for plotting. Aug 18 '21 at 22:11