我有如下数据:
example.df <- as.data.frame(matrix( c("height","fruit",0.2,0.4,0.7,
"height","veggies",0.3,0.6,0.8,
"height","exercise",0.1,0.2,0.5,
"bmi","fruit",0.2,0.4,0.6,
"bmi","veggies",0.1,0.5,0.7,
"bmi","exercise",0.4,0.7,0.8,
"IQ","fruit",0.4,0.5,0.6,
"IQ","veggies",0.3,0.5,0.7,
"IQ","exercise",0.1,0.4,0.6),
nrow=9, ncol=5, byrow = TRUE))
colnames(example.df) <- c("phenotype","predictor","corr1","corr2","corr3")
因此3x3变量之间基本上具有三种不同的相关性。我想将相关性的增加可视化如下:
ggplot(example.df, aes(x=phenotype, y=corr1, yend=corr3, colour = predictor)) +
geom_linerange(aes(x = phenotype,
ymin = corr1, ymax = corr3,
colour = predictor),
position = position_dodge(width = 0.5))+
geom_point(size = 3,
aes(x = phenotype, y = corr1, colour = predictor),
position = position_dodge(width = 0.5), shape=4)+
geom_point(size = 3,
aes(x = phenotype, y = corr2, colour = predictor),
position = position_dodge(width = 0.5), shape=18)+
geom_point(size = 3,
aes(x = phenotype, y = corr3, colour = predictor),
position = position_dodge(width = 0.5))+
labs(x=NULL, y=NULL,
title="Stackoverflow Example Plot")+
scale_colour_manual(name="", values=c("#4682B4", "#698B69", "#FF6347"))+
theme_minimal()
这给了我以下情节:
问题:
用BMI和IQ避开geom_point
形状的方式存在问题。它们都应该与颜色相同,如高度一样。
如何获得一个额外的图例,以显示圆形,十字形和正方形? (即在线上显示的三个不同的相关性:交叉=相关性1,正方形=相关性2,圆形=相关性3)。
图例现在显示一条线,一个圆,彼此交叉,而一条预测线(运动,水果,蔬菜)就足够了。
很抱歉,有多个问题,但是添加额外的图例(问题2)是最重要的,如果可以解决,我已经非常满意,剩下的就是奖金! :)
答案 0 :(得分:2)
看看以下内容对您有用吗?主要思想是将geom_point
层的数据帧从宽格式转换为长格式,并将映射相关性作为形状美感:
example.df %>%
ggplot(aes(x = phenotype, color = predictor, group = predictor)) +
geom_linerange(aes(ymin = corr1, ymax = corr3),
position = position_dodge(width = 0.5)) +
geom_point(data = . %>% tidyr::gather(corr, value, -phenotype, -predictor),
aes(y = value, shape = corr),
size = 3,
position = position_dodge(width = 0.5)) +
scale_color_manual(values = c("#4682B4", "#698B69", "#FF6347")) +
scale_shape_manual(values = c(4, 18, 16),
labels = paste("correlation", 1:3)) +
labs(x = NULL, y = NULL, color = "", shape = "") +
theme_minimal()
注意:颜色图例同时基于geom_linerange
和geom_point
,因此,图例键既包括线也包括点形状。尽管有可能摆脱第二个代码,但确实需要一些复杂的代码,因此,我认为绘图不会因此得到很大改善...