Making a Stacked BAR chart in ggplot from Excel file
1
0
Entering edit mode
2.3 years ago
Ap1438 ▴ 50
Cl  S1  S2  S3
A   39  42  40
B   15  20  18
C   15  4   10
D   4   5   5

I have a excel sheet with clade names A,B,C and D of 3 samples S1,S2 and S3 having relative abundance values shown above.

I want to make a Stacked Bar chart and used this code.

library("readxl")    
library(dplyr)    
library(ggplot2)    
library(scales)    
read_excel("relative_abundance(1).xlsx",sheet = "Only_P")     
ggplot(data, aes(fill=CL, lable=y, x='S1')) +     
    geom_bar(position="dodge", stat="identity")

But I didn't succeed. I am new to R and don't know much can anyone please help me.

I want to make a stacked bar chart as the image I have attached.

enter image description here

R ggplot • 2.3k views
ADD COMMENT
1
Entering edit mode

Please use the formatting bar (especially the code option) to present your post better. You can use backticks for inline code (`text` becomes text), or select a chunk of text and use the highlighted button to format it as a code block. If your code has long lines with a single command, break those lines into multiple lines with proper escape sequences so they're easier to read and still run when copy-pasted. I've done it for you this time.
code_formatting

ADD REPLY
0
Entering edit mode

Thank you for helping.I will keep in mind your valuable suggestions.

ADD REPLY
4
Entering edit mode
2.3 years ago

Your data is not in the correct format to be able to create the stacked barplot you have posted above. Here's a quick example of how you can get your data into that format (by "pivotting" the data from a wide-format, to a long format.) Assuming we have a data frame as such:

dt <- data.frame(CL = LETTERS[1:4],
               S1 = c(39, 15, 15, 4),
               S2 = c(42,20,4,5),
               S3 = c(40, 18, 10, 5))

head(dt)

CL S1 S2 S3
1  A 39 42 40
2  B 15 20 18
3  C 15  4 10
4  D  4  5  5

dt <- pivot_longer(dt, cols = -CL, names_to = "Samples", values_to = "Expression")

ggplot(dt, aes(x = Samples, y = Expression, fill = CL)) +
  geom_bar(stat = "identity")][1]

enter image description here

ADD COMMENT
0
Entering edit mode

It worked .Thank you for your valuable time and suggestion.

ADD REPLY

Login before adding your answer.

Traffic: 1895 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6