简体   繁体   中英

Stacked barplot with ggplot2 depending on two variables

I am trying to create a stacked barplot using ggplot2, which should represent the number of actions, divided in "clicked" or "dismissed" for each user.

The data look like this:

ID;User;All;clicked;dismissed
1;andre;3;3;0
2;bianca;23;14;9
3;corinna;51;31;20
4;pfeifer;8;7;1

Find below some my current approach, which totally useless until now, and some sample data

在此处输入图片说明

# Load data
Temp <- read.csv("http://pastebin.com/raw.php?i=LtYsjY89", header = TRUE, stringsAsFactors=FALSE, sep = ";")
# Load package
library(ggplot2)
# Plot
ggplot(Temp, aes(x=User, fill=All)) +
geom_bar() + 
scale_fill_gradient("Count", low = "green", high = "red") 

As you can see....the total number of the "All"-Variable is applied. What I try to realize: For each user a stacked bar should be created, which presents the the partitioning of the "All"-variable using the "clicked" and "dismissed" values. Thereby, the "clicked" and "dismissed" bar-part should have different colors.
Similar approaches suggest to melt the data (from wide to long), but I do not see the benefits for my use case.

You do need to melt the data (per @Gregor's comment). The reason is that to map "clicked" and "dismissed" to color, you need a single column that marks which counts come from "clicked" and which from "dismissed". Melting to long format is how you create that column.

library(reshape2)

Temp.m = melt(Temp, id.var=c("ID","User","All"))

# Plot
ggplot(Temp.m, aes(x=User, 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