R语言ggplot2:用annotate添加正方形和圆圈图例,x轴为因子型
要在R语言的ggplot2中使用annotate函数添加正方形和圆圈图例,需要先创建一个自定义的图例,并使用scale_shape_manual和scale_color_manual函数来指定图例的形状和颜色。
以下是一个示例代码:
library(ggplot2)
# 创建一个包含因子型数据的数据框
data <- data.frame(
x = factor(c('A', 'B', 'C')),
y = c(1, 2, 3)
)
# 创建一个包含正方形和圆圈的自定义图例
legend_data <- data.frame(
shape = c(15, 16),
color = c('black', 'red'),
label = c('Square', 'Circle')
)
# 创建ggplot对象并绘制散点图
p <- ggplot(data, aes(x = x, y = y)) +
geom_point(shape = 15, color = 'black') +
scale_x_discrete(labels = c('A', 'B', 'C'))
# 使用annotate函数添加自定义图例
p <- p +
annotate('point', x = 1.5, y = 4, shape = legend_data$shape[1], color = legend_data$color[1]) +
annotate('point', x = 2.5, y = 4, shape = legend_data$shape[2], color = legend_data$color[2]) +
annotate('text', x = 1.5, y = 4.5, label = legend_data$label[1]) +
annotate('text', x = 2.5, y = 4.5, label = legend_data$label[2])
# 使用scale_shape_manual和scale_color_manual指定图例的形状和颜色
p <- p +
scale_shape_manual(values = legend_data$shape) +
scale_color_manual(values = legend_data$color)
# 显示图形
print(p)
运行上述代码后,将会绘制一个带有正方形和圆圈图例的散点图,其中x轴为因子型数据。
原文地址: http://www.cveoy.top/t/topic/faib 著作权归作者所有。请勿转载和采集!