%useLatestDescriptors
%use lets-plot
There are several ways to show error ranges on a plot. Among them are
// This example was found at: www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)
val data = mapOf(
"supp" to listOf("OJ", "OJ", "OJ", "VC", "VC", "VC"),
"dose" to listOf(0.5, 1.0, 2.0, 0.5, 1.0, 2.0),
"length" to listOf(13.23, 22.70, 26.06, 7.98, 16.77, 26.14),
"len_min" to listOf(11.83, 21.2, 24.50, 4.24, 15.26, 23.35),
"len_max" to listOf(15.63, 24.9, 27.11, 10.72, 19.28, 28.93)
)
val p = letsPlot(data) {x="dose"; color="supp"}
p + geomErrorBar(width=.1) {ymin="len_min"; ymax="len_max"} +
geomLine {y="length"} +
geomPoint {y="length"}
// The errorbars overlapped, so use position_dodge to move them horizontally
val pd = positionDodge(0.1) // move them .05 to the left and right
p + geomErrorBar(width=.1, position=pd) {ymin="len_min"; ymax="len_max"} +
geomLine(position=pd) {y="length"} +
geomPoint(position=pd) {y="length"}
// Black errorbars - notice the mapping of 'group=supp'
// Without it, the errorbars won't be dodged!
p + geomErrorBar(color="black", width=.1, position=pd) {ymin="len_min"; ymax="len_max"; group="supp"} +
geomLine(position=pd) {y="length"} +
geomPoint(position=pd, size=5.0) {y="length"}
// Finished graph
// - fixed size
// - point shape # 21 is filled circle
// - position legend in bottom right
val p1 = p +
xlab("Dose (mg)") +
ylab("Tooth length (mm)") +
scaleColorManual(listOf("orange", "dark_green"), naValue="gray") +
ggsize(700, 400)
p1 + geomErrorBar(color="black", width=.1, position=pd) {ymin="len_min"; ymax="len_max"; group="supp"} +
geomLine(position=pd) {y="length"} +
geomPoint(position=pd, size=5.0, shape=21, fill="white") {y="length"} +
theme().legendJustification(1,0).legendPosition(1,0) +
ggtitle("The Effect of Vitamin C on Tooth Growth in Guinea Pigs")
// Plot error ranges on Bar plot
p1 +
geomBar(stat=Stat.identity, position=Pos.dodge, color="black") {y="length"; fill="supp"} +
geomErrorBar(color="black", width=.1, position=positionDodge(0.9)) {
ymin="len_min"
ymax="len_max"
group="supp"} +
theme().legendJustification(0,1).legendPosition(0,1)
// Thickness of the horizontal mid-line can be adjusted using `fatten` parameter.
p1 + geomCrossbar(fatten=5.0) {
ymin="len_min"
ymax="len_max"
middle="length"
color="supp"
}
p1 + geomLineRange(position=pd) {ymin="len_min"; ymax="len_max"; color="supp"} +
geomLine(position=pd) {y="length"}
// Point-range is the same as line-range but with an added mid-point.
p1 + geomPointRange(position=pd) {y="length"; ymin="len_min"; ymax="len_max"; color="supp"} +
geomLine(position=pd) {y="length"}
// Size of the mid-point can be adjuasted using `fatten` parameter - multiplication factor relative to the line size.
p1 + geomLine(position=pd) {y="length"} +
geomPointRange(position=pd, color="rgb(230, 230, 230)", size=5.0, shape=23, fatten=1.0) {
y="length"
ymin="len_min"
ymax="len_max"
fill="supp"
} +
scaleFillManual(listOf("orange", "dark_green"), naValue="gray")