Andy
Andy

Reputation: 485

Customize Barplot in base function barplot()

I have a date frame (df), with 2 columns: One numerical and one as.factor() with three levels:

I want to make a barplot() with each factor colored to it's respective group (easy), and change the order of the plot so each factor appears next to each other (this is where I'm stuck).

I followed the same logic as I would with a boxplot(), but it does not appear to work the same. I also tried following examples from several stackoverflow threads, including (but not limited to) this one:

But still can't get it to work.

Here is what I've tried, and it works with the boxplot function quite well:

df <- read.table("https://pastebin.com/raw/zaETq28M", header = T)

df$Treatment <- as.factor(df$Treatment)

levels(df$Treatment) # note: I would like to display order to be: Pre, Post, then Blank.

df$Treatment <- ordered(df$Treatment, levels = c("Pre","Post","Blank")) # set to the right order

barplot(df$Cq,names.arg = df$Treatment ,col = df$Treatment, ylim=c(0,30), main = "Not the right order bar plot", cex.main=2)

In total, I should have 66 individual bars (which I do), but somehow, the order of the graph is not what I set, and the groups are still separated. How can I simply get 3 distinct groups? Meaning, first show all "Pre", then all "post", followed by "blank"

General questions for future posts:

  1. How to get a get my graphs to be displayed on Stackoverflow when I post a question? For some reason, my posts never include my graphs.
  2. Also, any kind suggestion on using color blind pallet would be great, but I can just do this manually if needed. Just curious if there is an automatic way of doing it, so I do not need to set it manually in all my graphs

Thank you for your help

Upvotes: 0

Views: 81

Answers (1)

MarBlo
MarBlo

Reputation: 4534

Do you mean this? First the Pre, then Post then blank. Within each group order is preserved. Legend added with blank == No Treatment.

df <- read.table("https://pastebin.com/raw/zaETq28M", header = T)

df_Pre <- df[which(df$Treatment == 'Pre'),]
df_Post <- df[which(df$Treatment == 'Post'),]
df_Blank <- df[which(df$Treatment == 'Blank'),]
ddf <- rbind(df_Pre, df_Post, df_Blank)
ddf$color <- c(rep('blue', nrow(df_Pre)), rep('red', nrow(df_Post)), rep('magenta', nrow(df_Blank)))
barplot(ddf$Cq, col = ddf$color, names = rownames(ddf))
legend("bottomleft", 
       legend = c("Pre-Treatmen", "Post-Treatment", 'No Treatment'), 
       fill = c("darkblue", "red","magenta"))

Upvotes: 1

Related Questions