Combined positive and negative stacked line plots - r

I am trying to make a stacked line plot in ggplot2 with positive values stacked above the x-axis and negative values stacked separately below the x-axis. I have had success stacking each of the line types separately, but have not been able to have both on a single plot. I'm looking for some help on how I can do this, either by overlaying plots or doing something creative on a single plot.
My code below uses a simple ggplot with stacked geom_line plot. Half of the "Types" are positive values with respect to time and the other half of the "Types" are all negative values.
p <- ggplot(dataForm, aes(x=Time,y=Value,group=Type),colour=factor(Type))
p + geom_line(aes(fill = Type),position = "stack")
I have tried an alternative of specifying the positive and negative values separately without success:
p <- ggplot(dataForm, aes(x=Time,y=Value,group=Type),colour=factor(Type))
p + geom_line(data = data1,aes(fill = Type),position = "stack")
p + geom_line(data = data1,aes(fill = Type),position = "stack")
Any advice on how to do this is greatly appreciated. Thanks.

In the absence of a reproducible example, I adapted this example from learnr:
library(ggplot2)
library(plyr)
data = read.table(text="Time Type Value
1 a 8
2 a 10
3 a 10
4 a 5
5 a 3
1 b 9
2 b 5
3 b 7
4 b 8
5 b 3
1 c -3
2 c -1
3 c -5
4 c -4
5 c -7
1 d -11
2 d -3
3 d -9
4 d -6
5 d -6", header=TRUE)
p <- ggplot(data, aes(x=Time))
p <- p + geom_line(subset = .(Type %in% c('a', 'b')),
aes(y=Value, colour = Type),
position = 'stack')
p <- p + geom_line(subset = .(Type %in% c('c', 'd')),
aes(y=Value, colour = Type),
position = 'stack')
p
To produce this:
And, for good measure, an area chart with a horizontal line:
p <- ggplot(data, aes(x=Time))
p <- p + geom_area(subset = .(Type %in% c('a', 'b')),
aes(y=Value, fill=Type),
position = 'stack')
p <- p + geom_area(subset = .(Type %in% c('c', 'd')),
aes(y=Value, fill = Type),
position = 'stack')
p <- p + geom_hline(yintercept=0)
p

Related

How to customise the colors in stacked bar charts

Maybe a question someone already asked.
I have a data frame (dat) that looks like this:
Sample perc cl
a 30 0
b 22 0
s 2 0
z 19 0
a 12 1
b 45 1
s 70 1
z 1 1
a 60 2
b 67 2
s 50 2
z 18 2
I would like to generate a stacked barplot. To do this I used the following:
g = ggplot(dat, aes(x = cl, y = Perc,fill = Sample)
g + geom_bar(stat="identity", position = "fill", show.legend = FALSE) +
scale_fill_manual(name = "Samples", values=c("a"="blue","b" = "blue","s" = "gray","z" = "red"))`
Fortunately the colors are assigned correctly. My point is that the order of samples in the bar is from a to z from the top to the bottom of the bar but I would like a situation in which the gray is on the top without loss of continuity in the bar from the blue to the red. Maybe there's another way to color the bars and set the desired order.
The groups are plotted in the bars in the order of the factor levels. You can change the plotting order by changing the order of the factor levels in your call to aes with factor(var, levels(var[order])) like this:
library(ggplot2)
ggplot(dat, aes(x = cl, y = perc,
fill = factor(Sample, levels(Sample)[c(3,1,2,4)]))) +
geom_bar(stat="identity", position = "fill", show.legend = FALSE) +
scale_fill_manual(name = "Samples",
values=c("a"="blue","b" = "blue","s" = "gray","z" = "red"))

ggplot plotting all data as a single column when barplot plots everything correctly

My data is a single column like this:
Number Assigned Row
1 1
2 1
3 2
4 1
5 2
6 3
... ...
When I plot using barplot I get what I want:
However when I use ggplot + geom_bar I get this:
This is my code for ggplot:
count <- data.frame(alldata[[xaxis]])
ggplot(data=count, aes(x="My X Axis", y="My Y Axis")) +
geom_bar(stat="identity")
versus the code I use for barplot:
counts <- table(alldata[[xaxis]])
barplot(counts,
main = xaxis,
xlab = "Percentile",
cex.names = 0.8,
col=c("darkblue","red"), beside = group != "NA")
Say this is your data:
df <- data.frame(AssRow = sample(1:3, 100, T, c(0.2, 0.5, 0.3)))
head(df)
# AssRow
#1 2
#2 1
#3 2
#4 3
#5 2
#6 2
This will get you a bar chart of the count of each Assigned Row, and colour them:
ggplot(df, aes(x=AssRow, fill=as.factor(AssRow))) +
geom_bar()
To change the labels use xlab ylab/make the background prettier:
ggplot(df, aes(x=AssRow, fill=as.factor(AssRow))) +
geom_bar() +
xlab("My X-label") +
ylab("My Y label") +
theme_bw()
Output:

Remove Factors with no data in facet grouping variable

I have the following data :
data <- data.frame(x = letters[1:6],
group = rep(letters[1:2], each = 3),
y = 1:6)
x group y
1 a a 1
2 b a 2
3 c a 3
4 d b 4
5 e b 5
6 f b 6
And I would like to plot y ~ x and split into facets by groups with ggplot2.
ggplot(data, aes(x, y)) +
geom_bar(stat = "identity") +
facet_grid(group ~ .)
The problem is that some tuples (x; group) don't exist in my data(for example there is no data for x = a && group = b) , but they are kept in the x-axis of both facets so I would like to remove them and then remove white spaces in the facets when factors are missing in respective groups.
I thought scales = "free_x" or drop = TRUE could do the trick but I couldn't manage to do it.
Any help would be appreciated, Thanks !
Use facet_wrap instead
ggplot(data, aes(x, y)) +
geom_col() +
facet_wrap(~group, scales = 'free', nrow = 2, strip.position = 'right')
also note geom_col as an alternative to using identity

Exploded 180 degree pie chart in R ggplot or ggvis (image included)?

Given a dataset with a factor column (X1) and a subtotal column (X2)
X1 X2
1 1 12
2 2 200
3 3 23
4 4 86
5 5 141
I would like to create a graphic like this:
which gives x2 as a percentage of the X2 total, divided by X1.
Edit: clarity and adding dataset for reproducability
For example
set.seed(1234)
df <- data.frame(x = 1:6)
df$y <- runif(nrow(df))
df$type <- sample(letters, nrow(df))
ggplot(df, aes(x+-.5, y, fill=type)) +
geom_bar(stat="identity", width=1) +
coord_polar(start = pi/2) +
scale_x_continuous(limits = c(0, nrow(df)*2)) +
geom_text(aes(label=scales::percent(y))) +
ggthemes::theme_map() + theme(legend.position = c(0,.15))
gives you

In a ggplot2 geom_tile plot, is it possible to dodge the positions of tiles?

I'm trying to produce a bar plot where the bars fade vertically according to a third variable, and I'm using geom_tile to enable this. However, I have multiple bars for a given category on the x-axis, and I'd like to dodge their positions to put alike x values together in groups of bars which don't overlap.
Is it possible to use position='dodge' or similar with geom_tile and, if so, what's wrong with my syntax?
a <- data.frame(x = factor(c(rep('a',5), rep('a',5), rep('b',5), rep('c',5))),
y = c(1:5, 1:5, 1:5, 1:5),
z = c(5:1, c(5,4,4,4,1), 5:1, 5:1)
)
ggplot(a, aes(x = x, y = y, group = x)) +
geom_tile(aes(alpha = z, fill = x, width = 1),
position = 'dodge')
The example data frame a looks like this:
x y z
1 a 1 5
2 a 2 4
3 a 3 3
4 a 4 2
5 a 5 1
6 a 1 5
7 a 2 4
8 a 3 4
9 a 4 4
10 a 5 1
11 b 1 5
12 b 2 4
13 b 3 3
14 b 4 2
15 b 5 1
16 c 1 5
17 c 2 4
18 c 3 3
19 c 4 2
20 c 5 1
...and the resulting graph from the current code has no gaps between the x values, and the two where x is a are drawn on top of one-another:
I want those two bars where x is 'a' to be drawn as separate bars.
This is a mock-up of what I want the result to look like. The data are not correct for either of the a columns but it shows the grouping on the x-axis which is desired:
EDIT 2
To get your desired effect, use geom_bar() but be sure to change the y data to indicate the bar height, in this case 1. The reason is that the bars get stacked, so there is no need to specify the y-axis position, but instead specify the height.
Try this:
library(ggplot2)
a <- data.frame(x = factor(c(rep('a',5), rep('a',5), rep('b',5), rep('c',5))),
y = 1,
z = c(5:1, c(5,4,4,4,1), 5:1, 5:1)
)
a$bar <- rep(1:4, each=5)
ggplot(a, aes(x = factor(bar), y=y, fill=x, alpha=z)) +
geom_bar(stat="identity") +
facet_grid(~x, space="free", scale="free")
You should get:
EDIT 1
You can get close to what you describe by:
Explicitly adding another column that differentiates different bars in the same category
Using faceting
For example:
a$bar <- rep(1:4, each=5)
ggplot(a, aes(x = factor(bar), y = y, fill=x, alpha=z)) +
geom_bar(stat="identity", position="dodge") +
facet_grid(~x, space="free", scale="free")
ORIGINAL
You can use geom_bar() for this, by using stat="identity":
ggplot(a, aes(x = x, y = y, fill=x, alpha=z)) +
geom_bar(stat="identity", position="dodge")

Resources