r - Custom line in barplot (multiple barplots) -
my data frame:
n p e s w1 3.5 3.5 3.4 3.5 w2 3.4 3.7 3.6 3.5 w3 3.5 3.4 3.5 3.5 w4 3.5 3.4 3.5 3.5 w5 3.5 3.4 3.5 3.5 w6 3.5 3.4 3.5 3.5 w7 3.5 3.4 3.5 3.5 w8 3.5 3.4 3.5 3.5
and code barplot
mat <- as.matrix(t(tabela.matrix)) qw <- barplot(mat, beside = true, axisnames = false, ylim = c(0, 6), col = c("yellow", "deepskyblue1", "yellowgreen", "orchid4")) text(colmeans(qw[2:3, ]), -0.25, labels = colnames(mat), xpd = true, srt = 15) text(qw, 0, round(as.matrix(t(tabela.matrix)), 1), cex = 1, pos = 3, srt = 90) legend(3.2, -0.6, c("n","p","e", "s"), fill = c("yellow", "deepskyblue1", "yellowgreen", "orchid4"), horiz = true, xpd = true)
so on barplot need add line
indicates subtraction: max-min values per row. using below code subtraction.
max.tmp <- apply(df, 1, max) min.tmp <- apply(df, 1, min) substr.tmp <- max.tmp - min.tmp
now add red line indicating values in substr.tmp
. code lines()
doesn't work.
my output (red line) should "look" (it picture form excel , interested in adding line, not data in picture itself)
a dput
of data:
structure(c(3.46666666666667, 3.35, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.45555555555556, 3.7, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.40769230769231, 3.57692307692308, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.51122994652406, 3.5156862745098, 3.49090909090909, 3.49090909090909, 3.49090909090909, 3.49090909090909, 3.49090909090909, 3.49090909090909 ), .dim = c(8l, 4l), .dimnames = list(c("a", "b", "c", "d", "e", "f", "g", "h"), null))
with data.table
, ggplot2
packages follows:
library(data.table) df2 <- melt(setdt(df), id="name") df2[, difference := max(value) - min(value), = name] library(ggplot2) ggplot(df2, aes(x=name, y=value, fill=variable)) + geom_bar(stat="identity", position="dodge") + geom_line(aes(x=name, y=difference, group=1), size=1.5, color="red") + scale_x_discrete(expand = c(0,0)) + scale_y_continuous(expand = c(0,0), limits = c(0,4)) + scale_fill_manual(breaks = c("v1", "v2", "v3", "v4"), values = c("yellow", "deepskyblue1", "yellowgreen", "orchid4")) + theme_bw()
this gives:
used data:
m <- structure(c(3.46666666666667, 3.35, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.45555555555556, 3.7, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.36666666666667, 3.40769230769231, 3.57692307692308, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.53846153846154, 3.51122994652406, 3.5156862745098, 3.49090909090909, 3.49090909090909, 3.49090909090909, 3.49090909090909, 3.49090909090909, 3.49090909090909 ), .dim = c(8l, 4l), .dimnames = list(c("a", "b", "c", "d", "e", "f", "g", "h"), null)) df <- as.data.frame(m) df$name <- rownames(df)
Comments
Post a Comment