我正在尝试手动组合ggplot2 :: geom_pointrange()绘图与通过ggplot2 :: geom_linerange()实现的条形图和基于ggplot2 :: geom_text()的图例。最后,我希望有一个没有任何标签的情节和条形图。很抱歉这个问题很长,但我看不到进一步缩短的问题。
这是我到目前为止尝试过的代码
library(dplyr)
library(ggplot2)
data(mpg)
# calculate average fuel consumption based on arbitrary assumption of equal
# city/highway share
mpg <- mutate(mpg, avg = (cty + hwy)/2)
# compute quantils
mpg_by_class <- group_by(mpg, class) %>%
summarise(q10 = quantile(avg, 0.1),
q90 = quantile(avg, 0.9),
med = median(avg))
# compute some cross-class values
mpg_median <- median(mpg$avg)
# plotting ----
# base plot
the_plot <- ggplot() +
geom_pointrange(data = mpg_by_class,
aes(x = class, ymin = q10, ymax = q90, y = med)) +
theme_classic() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
# add a bar on the right
the_plot <- the_plot +
# build the bar
geom_linerange(aes(x = "Y",
ymin = min(mpg_by_class$q10),
ymax = mpg_median), size = 5, colour = "green",
show.legend = FALSE) +
geom_linerange(aes(x = "Y",
ymin = mpg_median,
ymax = max(mpg_by_class$q90), size = 5, colour = "red"),
show.legend = FALSE) +
labs(x = "", y = "mpg") +
# # add labels
geom_text(aes(x = "Z", y = mean(c(min(mpg_by_class$q10), mpg_median)),
label = "shitty"), hjust = 0) +
geom_text(aes(x = "Z", y = mean(c(max(mpg_by_class$q90), mpg_median)),
label = "less shitty"), hjust = 0)
print(the_plot)
“类”可能随数据而变化,右侧彩色条中不同元素的数量也会随之变化。
这里实际上有两个问题: