简体   繁体   中英

Stacked bar in R

I have a table exported in csv from PostgreSQL and I'd like to create a stacked bar graph in R. It's my first project in R.

Here's my data and what I want to do:

在此输入图像描述

It the quality of the feeder bus service for a certain provider in the area. For each user of the train, we assign a service quality based of synchronization between the bus and the train at the train stations and calculate the percentage of user that have a ideal or very good service, a correct service, a deficient service or no service at all (linked to that question in gis.stackexchange )

So, It's like to use my first column as my x-axis labels and my headers as my categories. The data is already normalized to 100% for each row.

In Excel, it's a couple of clicks and I wouldn't mind typing a couple of line of codes since it's the final result of an already quite long plpgsql script... I'd prefer to continue to code instead of moving to Excel (I also have dozens of those to do).

So, I tried to create a stacked bar using the examples in Nathan Yau's "Visualize This" and the book "R in Action" and wasn't quite successful. Normally, their examples use data that they aggregate with R and use that. Mine is already aggregated.

So, I've finally come up with something that works in R:

在此输入图像描述

but I had to transform my data quite a bit:

在此输入图像描述

I had to transpose my table and remove my now-row (ex-column) identifier.

Here's my code:

# load libraries
library(ggplot2)
library(reshape2)

# load data
stl <- read.csv("D:/TEMP/rabat/_stl_rabattement_stats_mtl.csv", sep=";", header=TRUE)

# reshape for plotting
stl_matrix <- as.matrix(stl)

# make a quick plot
barplot(stl_matrix, border=NA, space=0.1, ylim=c(0, 100), xlab="Trains", ylab="%",
main="Qualité du rabattement, STL", las = 3)

Is there any way that I could use my original csv and have the same result?

I'm a little lost here...

Thanks!!!!

It appears that you transposed the matrix manually. This can be done in R with the t() function.

Add the following line after the as.matrix(stl) line:

stl_matrix <- t(stl_matrix)

Try the ggplot2 and reshape library. You should be able to get the chart you want with

stl$train_order <- as.numeric(rownames(stl))
stl.r <- melt(stl, id.vars = c("train_no", "train_order"))
stl.r$train_no <- factor(
    stl.r$train_no, 
    levels = stl$train_no[order(stl$train_order)])    
ggplot(stl.r, aes(x = factor(train_no), y = value, fill = variable)) + geom_bar(stat = 'identity')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM