使用以下数据,我正在尝试为演示文稿创建图表:
name = c("Phil", "Ian", "Leslie", "Darla", "Silvia", "Ron", "Emily", "Jack")
score = c(73.8, 73.5, 70.3, 68.9, 65.3, 61.4, 55.2, 54.3)
tx = c(0,0,1,0,0,0,0,0)
test1 <- data.frame(name, score, tx)
该图表旨在将每个点显示为一个大圆,其中圆点内的绘图点的值。红色虚线表示绘制的值的平均值。灰色矩形表示平均值附近的标准偏差。以下是我用来创建图表的代码:
library(ggplot2)
library(scales)
cols <- c("1" = "#ff7f0e", "0" = "#1f77b4")
txctrl <- c("1" = "#ffffff", "0" = "#000000")
ggplot(test1, aes(x=score, y=reorder(name,score))) +
geom_vline(aes(xintercept=mean(score)), colour="red", linetype="dashed", size=1) +
geom_point(aes(colour = factor(tx), size=0), show.legend = FALSE) +
annotate("rect", xmin=(mean(test1$score)-sd(test1$score)), xmax=(mean(test1$score)+sd(test1$score)), ymin=-Inf, ymax=Inf, alpha=0.5, fill="grey90") +
# geom_label(aes(label=score), colour=txctrl, fontface = "bold") +
scale_colour_manual(values=cols) +
scale_size(range=c(11,11)) +
xlim(52,78) +
geom_text(aes(label=score), hjust=0.5, vjust=0.5, size=5, label=round(test1$score, digits = 0)) +
labs(y='Name', x='Score') +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(color=NA),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.text.y = element_text(size=14),
axis.title.y = element_blank())
以下代码的结果如下:
我遇到的问题是矩形正在淡化绘图点的颜色。 如何让灰色矩形出现在绘图点和值标签后面?
逐层工作,我设法让虚线平均线位于情节点后面。当我尝试在标识绘图点的图层之前移动带注释的矩形时,我收到错误。
答案 0 :(得分:1)
尝试使用geom_rect而不是annotate。然后,您将要从aes功能中删除您的美学。我不能说它为什么会产生错误,但确实如此。
你可以在下面学习,看看我的意思。
ggplot(test1, aes(x=score, y=reorder(name,score))) +
geom_rect(xmin=(mean(score)-sd(score)), xmax=(mean(score)+sd(score)),ymin=-Inf, ymax=Inf, alpha=0.5,fill="grey90") +
geom_vline(aes(xintercept=mean(score)), colour="red", linetype="dashed", size=1) +
geom_point(aes(colour = factor(tx), size=0), show.legend = FALSE) +
scale_colour_manual(values=cols) +
scale_size(range=c(11,11)) +
xlim(52,78) +
geom_text(aes(label=score), hjust=0.5, vjust=0.5, size=5, label=round(test1$score, digits = 0)) +
labs(y='Name', x='Score') +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(color=NA),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.text.y = element_text(size=14),
axis.title.y = element_blank())