I am just learning R
and trying to reproduce something that I can easily create in Excel
via a PivotTable
. I have the data below that lists state names and their status. I want to make a horizontal bar chart that shows the state name on the Y axis and the percentage below on the X axis.
state_name status
State 1 above
State 1 above
State 1 below
State 1 below
State 1 below
State 1 above
State 1 below
State 1 below
State 1 below
State 1 above
State 2 above
State 2 NA
State 2 NA
State 2 NA
State 2 NA
State 3 below
State 3 above
State 3 above
State 3 above
State 3 below
State 3 above
State 3 below
State 3 below
State 3 above
I can load the data but am not sure how to write the code to subset and create percentages.
Here is my poor attempt,
ggplot(data = subset(data, !is.na(status)), aes(y=state_name, x=count(status[below])/count(status))) +
geom_bar(stat="identity")
Any help would be greatly appreciated. I learn best through examples.
You can use prop.table
for getting the percantages as,
data_perc <- as.data.frame(prop.table(table(data), 1))
data_perc <- data_perc[data_perc$status=="below",]
ggplot(data= data_perc, aes(x=state_name,y= Freq ,fill=state_name)) +
geom_bar(stat="identity") +
coord_flip() +
ggtitle("My Bar Chart")
gives,
Data:
data <- read.table(text="state_name status
State1 above
State1 above
State1 below
State1 below
State1 below
State1 above
State1 below
State1 below
State1 below
State1 above
State2 above
State2 NA
State2 NA
State2 NA
State2 NA
State3 below
State3 above
State3 above
State3 above
State3 below
State3 above
State3 below
State3 below
State3 above",header=T)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments