Home > Back-end >  Barplot in R with stacked columns and custom x axis labels
Barplot in R with stacked columns and custom x axis labels

Time:08-09

I am new to R and I have the following database structure:

names <- c("a","b","c","d")
val1 <- c(1,2,3,4)
val2 <- c(2,3,4,5)
df <- cbind(val1,val2)
rownames(df) <- names
df

I want to barplot the two value columns (stacking the columns next to each other) and have the rownames of the dataframe as x labels.

The excel plot would look like this:

enter image description here Any hint on how to achieve this? Many thanks in advance.

CodePudding user response:

Having the bars next to each other is a "dodged" bar plot, not a "stacked" bar plot, which implies the bars are positioned on top of each other. In base R you could do:

barplot(t(df), beside = TRUE, col = c("#4f81bd", "#c0504d"))

enter image description here

This is a dodged bar plot.

If you want a stacked bar plot, it would be:

barplot(t(df), beside = FALSE, col = c("#4f81bd", "#c0504d"))

enter image description here If you want full customization of all the graphical elements, using ggplot is a better approach. For example, if you really love that MS Excel look:

library(tidyverse)

df %>%
  as.data.frame() %>%
  rownames_to_column() %>%
  pivot_longer(-1) %>%
  ggplot(aes(rowname, value, fill = name))  
  geom_col(position = position_dodge(width = 0.75), width = 0.5)  
  theme_minimal(base_size = 16)  
  scale_fill_manual(values = c("#4f81bd", "#c0504d"), 
                    labels = c('Series1', 'Series2'), name = NULL)  
  scale_y_continuous(breaks = 0:6, limits = c(0, 6), name = NULL)  
  labs(x = NULL, title = 'Chart title')  
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        legend.position = 'bottom',
        plot.title = element_text(hjust = 0.5))

enter image description here

CodePudding user response:

BTW, using base R you need to make a matrix and transpose for it to work right...

 names <- c("a","b","c","d")
 val1 <- c(1,2,3,4)
 val2 <- c(2,3,4,5)
 df <- cbind(val1,val2)
 rownames(df) <- names
 barplot(t(as.matrix(df)), beside=TRUE)

I was wrong above: t() works fine with dfs, so no as.matrix needed.

  • Related