Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating grouped bar chart

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading