我想为
Fair
和Good
添加“A”,为Very good
和Premium
添加“B”,为Ideal
钻石添加“C”,但我的文字很混乱。
library(dplyr; ggplot2)
注释文本
ann_text <- expand.grid(
x = c(1.5, 3.5, 5),
y = 6000,
label = c("A", "B", "C"),
clarity = c("I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"),
cut = LETTERS[4:10])
)
点的虚拟 df
price.avg <- diamonds %>%
group_by(cut, color) %>%
summarise(price = mean(price))
主线
diamonds %>%
ggplot() +
geom_bar(aes(x = cut, fill = clarity)) +
facet_wrap(~ color) +
ylab("Count") +
xlab("Cut") +
geom_point(data = price.avg, aes(x = cut, y = price, col = "")) +
scale_y_continuous(sec.axis = sec_axis(~. * 1, name = "price")) +
geom_vline(xintercept=c(2, 4) + .5, lwd=.5, colour="black") +
geom_text(data = ann_text, aes(x = x, y = y, label = label)) +
scale_color_manual(name = "", label = "Average price", values = "black")
感谢任何线索。
对于注释数据框,我想你不需要做
expand.grid
,每个标签一行就可以了。因此我使用 ann_text2
进行标签注释。以后如果你想避免标签重叠,使用geom_text(check_overlap = TRUE)
。
library(dplyr)
library(ggplot2)
ann_text2 <- data.frame(x = c(1.5, 3.5, 5),
y = 6000,
label = LETTERS[1:3])
price.avg <- diamonds %>%
group_by(cut, color) %>%
summarise(price = mean(price))
diamonds %>%
ggplot() +
geom_bar(aes(x = cut, fill = clarity)) +
facet_wrap(~ color) +
ylab("Count") +
xlab("Cut") +
geom_point(data = price.avg, aes(x = cut, y = price, col = "")) +
scale_y_continuous(sec.axis = sec_axis(~. * 1, name = "price")) +
geom_vline(xintercept=c(2, 4) + .5, lwd=.5, colour="black") +
geom_text(data = ann_text2, aes(x = x, y = y, label = label), check_overlap = T) +
scale_color_manual(name = "", label = "Average price", values = "black")