I would like to create a stacked chart using ggplot2 and geom_bar.
Here is my source data:
Rank F1 F2 F3 1 500 250 50 2 400 100 30 3 300 155 100 4 200 90 10
I want a stacked chart where x is the rank and y is the values in F1, F2, F3.
# Getting Source Data sample.data <- read.csv('sample.data.csv') # Plot Chart c <- ggplot(sample.data, aes(x = sample.data$Rank, y = sample.data$F1)) c + geom_bar(stat = "identity")
This is as far as i can get. I'm not sure of how I can stack the rest of the field values.
Maybe my data.frame is not in a good format?
A stacked bar graph (or stacked bar chart) is a chart that uses bars to show comparisons between categories of data, but with ability to break down and compare parts of a whole. Each bar in the chart represents a whole, and segments in the bar represent different parts or categories of that whole.
A segmented horizontal bar chart is a type of stacked bar chart. It is also called a 100% stacked bar graph because each horizon bar represents 100% of the discrete data value and all the bars are of the same length while numerical variations are indicated in percentages.
First, enter and highlight the data. Most versions of Excel: Click on Chart. Click Insert, then click Stacked Area. Mac Excel 2011: Click on Chart, then Stacked Area.
We should first select the range of cells (rows and columns) containing the data to be presented using a stacked column graph. That would be the input data for the chart. Then, click on “Recommended Charts,” as shown below. Select Columns-> Stacked Column Chart from the given list -> Click “OK.”
You need to transform your data to long format and shouldn't use $
inside aes
:
DF <- read.table(text="Rank F1 F2 F3 1 500 250 50 2 400 100 30 3 300 155 100 4 200 90 10", header=TRUE) library(reshape2) DF1 <- melt(DF, id.var="Rank") library(ggplot2) ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + geom_bar(stat = "identity")
You said :
Maybe my data.frame is not in a good format?
Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.
Using reshape2
for example , you do this using melt
:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
Then you get your barplot:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) + geom_bar(stat='identity')
But using lattice
and barchart
smart formula notation , you don't need to reshape your data , just do this:
barchart(F1+F2+F3~Rank,data=dat)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With