Home > Blockchain >  Creating grouped bar chart
Creating grouped bar chart

Time:01-08

I'm trying to make groupped bar chart in r but it doesn't work. In other words, i only could get ugly stacked chart which is not enough. I'm giving the screenshots of my data and group chart example which I have created in excel. Sure it is not possible to create a same chart but it's just my idea and close one is enough.

I'm also gonna give the example of visualisation which I have got after the wrote code in r.

Data:

enter image description here

Bar chart that I want to create(close one is enough):

enter image description here

My code

ggplot(PV_cluster1, aes(Years, y= c(MSFT, ATVI, AMOT),  group=3))   
  geom_bar(position = "stack", stat = "identity", mapping = aes( y= MSFT, group=1, col="MSFT"))  
  geom_bar(position = "stack", stat = "identity",mapping = aes( y= ATVI, group=2, col="ATVI"))   
  geom_bar(position = "stack", stat = "identity",mapping = aes( y= AMOT, group=3, col="AMOT")) 
  scale_y_continuous(breaks=c(-20, 0, 20, 40, 60, 80, 100))  
  theme_bw()   
  labs(title = "Cluster 1 stocks", subtitle = "MSFT, ATVI, AMOT", colour="Stocks", y= "Price Variance")

That's what I got after this code

enter image description here

CodePudding user response:

When working with ggplot2 you got to have tidy format. This is how to do it, the details should be clear.

library(tidyverse)

df <- structure(list(MSFT = c(21.87849, 16.505711, 39.74112, 20.21909, 58.259263), 
               ATVI = c(94.26838, -3.232714, 73.87468, -27.2118, 27.359807), 
               AMOT = c(14.07271, -13.929934, 48.61813, 28.48922, 9.070286), 
               Years = c("2015", "2016", "2017", "2018", "2019")), 
          row.names = 2:6, class = "data.frame") 
df %>%
  pivot_longer(
    cols = MSFT:AMOT,
    values_to = "value",
    names_to = "stock"
  ) %>%
  ggplot(aes(x=Years, y=value, fill=stock)) 
  geom_col(position = "dodge")

Created on 2023-01-07 with reprex v2.0.2

  • Related