我想在boxplot的一侧添加几个标签,如image1。我在ggplot(image2)中生成了盒子图。请帮我解决问题。
请检查我的代码以生成boxplot,
$(document).ready(function() {
// Get all elements
$('.carosuelProperties').each(function() {
// Set the reference to the current element
var current = $(this);
// Find the image
var image = current.find('img');
// Set the background image
current.css('background-image', 'url(' + image.attr('src') + ')');
});
});
谢谢, SJB。
答案 0 :(得分:3)
我们可以使用ggrepel
包,并创建我们需要的文本和位置。
我们首先需要计算标签的y
位置,我希望我能做到正确,如果需要可以改变。
请注意,在此表单中,绘图的许多部分都是硬编码的,在某些情况下无法使用,特别是xlim
是为我的特定屏幕手动挑选的,可能需要进行调整。< / p>
library(ggplot2)
library(ggrepel)
d <- data.frame(runif(100, min=0, max=10000))
names(d) <- "randnum"
first_quantile <- quantile(d$randnum, .25)
third_quantile <- quantile(d$randnum, .75)
inner_fence <- third_quantile + (third_quantile - first_quantile) * 1.5
outer_fence <- inner_fence + (third_quantile - first_quantile) * 1.5
fences <- data.frame(labels = c('first quartile', 'third quartile', 'inner fence', 'outer fence'),
y = c(first_quantile, third_quantile,
inner_fence, outer_fence))
ggplot(d, aes_string(x=factor(0), y=d$randnum)) +
geom_boxplot() +
geom_jitter(size = 3, alpha = 0.5, color = "tomato") +
geom_text_repel(data = fences, aes(x = 1.45, y = y, label = labels), nudge_x = 500, segment.color = 'green', xlim = c(NA, 2)) +
coord_cartesian(xlim = c(0.85,1.5)) +
theme_classic() +
theme(legend.position = "none", axis.title =element_blank(),
axis.text.x =element_blank(), axis.ticks.x=element_blank())
由reprex package(v0.2.0)创建于2018-05-16。
答案 1 :(得分:2)
或者你可以尝试
# your data
set.seed(1234)
d <- data.frame(runif(100, min=0, max=10000))
names(d) <- "randnum"
# the plot
box1 <- ggplot(d, aes_string(x=factor(0), y=d$randnum)) +
geom_boxplot(alpha = 0) +
geom_jitter(size = 3, alpha = 0.5, color = "tomato")
# the data for the annotation
d2 <- data.frame(y=boxplot(d,plot = F)$stats,
x=1.4,
xend=1.5)
d2 <- rbind.data.frame(d2, c(d2[4,1]+ (d2[4,1] - d2[2,1]) * 1.5, 1.4, 1.5))
d2 <- rbind.data.frame(d2, c(d2[6,1]+ (d2[4,1] - d2[2,1]) * 1.5, 1.4, 1.5))
d2$label <- c("Min", "1Q", "Median", "3Q", "Max", "Inner", "Outer")
# and the plot
box1 + scale_y_continuous(name="", sec.axis =dup_axis(name = "",
breaks = d2$y,
labels = d2$label)) +
geom_segment(aes(x=x, y=y, xend=xend, yend=y), data = d2, inherit.aes = F)