我正在尝试使用数字(1,2,3,...)在R(ggplot2
)中的散点图中标记点,然后将这些数字与图例中的名称相匹配(1 - Alpha,2 - 布拉沃,3 - 查理......),作为处理剧情中太多太长标签的一种方式。
我们假设这是a.df:
Name X Attribute Y Attribute Size Attribute Color Attribute Alpha 1 2.5 10 A Bravo 3 3.5 5 B Charlie 2 1.5 10 C Delta 5 1 15 D
这是一个标准的散点图:
ggplot(a.df, aes(x=X.Attribute, y=Y.Attribute, size=Size.Attribute, fill=Colour.Attribute, label=Name)) + geom_point(shape=21) + geom_text(size=5, hjust=-0.2,vjust=0.2)
有没有办法改变它如下?
在下一步中,我想为点大小和颜色指定其他属性,这可能会排除一些“黑客”。
答案 0 :(得分:1)
这非常hacky,但可能有所帮助。情节标签只是由geom_text
添加,为了产生图例,我将颜色映射到数据中的标签。然后,为了停止被着色的点,我用scale_colour_manual
覆盖它,您可以在其中设置点的颜色以及图例上的标签。最后,我通过设置alpha = 0来设置图例中的点,以及通常位于theme()
中的点后面的正方形。
dat <- data.frame(id = 1:10, x = rnorm(10), y = rnorm(10), label = letters[1:10])
ggplot(dat, aes(x, y)) + geom_point(aes(colour = label)) +
geom_text(aes(x = x + 0.1, label = id)) +
scale_colour_manual(values = rep("black", nrow(dat)),
labels = paste(dat$id, "=", dat$label)) +
guides(colour = guide_legend(override.aes = list(alpha = 0))) +
theme(legend.key = element_blank())
答案 1 :(得分:1)
这是另一种解决方案,它将标签绘制为geom_text
。我借来的
ggplot2 - annotate outside of plot
library(MASS) # for Cars93 data
library(grid)
library(ggplot2)
d <- Cars93[1:30,]
d$row_num <- 1:nrow(d)
d$legend_entry <- paste(" ", d$row_num, d$Manufacturer, d$Model)
ymin <- min(d$Price)
ymax <- max(d$Price)
y_values <- ymax-(ymax-ymin)*(1:nrow(d))/nrow(d)
p <- ggplot(d, aes(x=Min.Price, y=Price)) +
geom_text(aes(label=row_num)) +
geom_text(aes(label=legend_entry, x=Inf, y=y_values, hjust=0)) +
theme(plot.margin = unit(c(1,15,1,1), "lines"))
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)