Home > OS >  Group bar plots together using ggplot2
Group bar plots together using ggplot2

Time:09-17

I have data looking like:

Accounts Income Expense Benefit
selling food 338.96 43.18 295.78
selling books 2757.70 2341.66 416.04
selling bikes 1369.00 1157.00 212.00

and I would like to get a combined bar plot such as this:

enter image description here

To do that, I wrote this R script:

## Take a data set in and produces a bar chart

## Get rid of the column containing account names to only keep values:
values <- as.matrix(data)[,-1]

## Convert strings to numbers:
values <- apply(values, 2, as.numeric)

## Transpose the matrix:
values <- t(values)

## Vertical axis labels are taken from the first column:
accountNames <- data$Accounts

## The legend is the first row except the first cell:
legend <- tail(names(data), -1)

## Colors are taken randomly
colors <- rainbow(length(legend))

## Increase left margin to fit horizontal axis labels:
par(mar=c(5,8,4,2) .1)

## Axis labels are drawn horizontal:
par(las=1)

barplot(
  values,
  names.arg=accountNames,
  col=colors,
  beside = TRUE,
  legend = legend,
  horiz = TRUE
)

I would like to modernize this bar chart with ggplot2 which I use for other graphs of the same document. The documentations I found to do that always assume data in a very different shape and I don't know R enough to find out what to do by myself.

CodePudding user response:

Here is the basic,then you can customize the plot the way you want

Libraries

library(tidyverse)

Data

data <-
tibble::tribble(
        ~Accounts, ~Income, ~Expense, ~Benefit,
   "selling food",  338.96,    43.18,   295.78,
  "selling books",  2757.7,  2341.66,   416.04,
  "selling bikes",    1369,     1157,      212
  )

Code

data %>%
  #Pivot Income, Expense and Benefit
  pivot_longer(cols = -Accounts) %>% 
  #Define each aesthetic
  ggplot(aes(x = value, y = Accounts, fill = name)) 
  # Add geometry column 
  geom_col(position = position_dodge())

Results

enter image description here

CodePudding user response:

1.Bring your data in long format with pivot_longer

2.Then plot with geom_bar and

  1. Use coord_flip
library(tidyverse)
df %>% 
    pivot_longer(
        cols= -Accounts,
        names_to = "Category",
        values_to = "values"
    ) %>% 
    ggplot(aes(Accounts, y=values, fill = Category))  
    geom_bar(stat="identity", position = "dodge") 
    coord_flip()  
    theme_classic()

enter image description here

  • Related