I have the following data :
mydata <- data.frame(x = c("UK1", "UK2", "UK3", "UK4", "UK5", "UK6", "UK7"),
n = c(50, 55, 58, 64, 14, 18, 45),
F = c(-6, 17, 26, -37, 44, -22, 15),
z = c("a", "a", "b", "a" , "b", "b", "a"))
I want to create a ggplot (bar chart) of column x (x axis) against column n (y-axis) colour split by column z. The tricky part is I want to bar chart to be going up the way if the value in F is positive and down the way if negative. Is this possible with ggplot?
Solution using sign
:
You can use sign()
to extract sign of F
and multiply that by n
: n * sign(F)
library(ggplot2)
mydata <- data.frame(x = c("UK1", "UK2", "UK3", "UK4", "UK5", "UK6", "UK7"),
n = c(50, 55, 58, 64, 14, 18, 45),
F = c(-6, 17, 26, -37, 44, -22, 15),
z = c("a", "a", "b", "a" , "b", "b", "a"))
ggplot(mydata, aes(x, n * sign(F), fill = z)) +
geom_bar(stat = "identity", position = "dodge")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments