如何在ggplot2中根据列值条件设置scale_shape_manual参数?
解决方案
核心问题
scale_shape_manual()的values参数需要接收命名向量(或与因子水平顺序匹配的向量)来定义映射规则,而case_when()是逐行处理数据的函数,无法直接生成符合要求的映射关系;另外代码中未定义unicode对象,也会导致报错。
修正后的代码
library(ggplot2) library(dplyr) adrs4 <- structure(list(subjid = structure(c(1L, 1L, 1L, 1L, 1L, 1L), levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"), class = "factor"), ady = c(38, 84, 111, 111, 242, 242), avalc = structure(c(3L, 4L, 6L, 6L, 7L, 7L), levels = c("CR", "PR", "SD", "PD", "On-treatment", "EOT", "Death"), class = "factor"), trtedy = c(0, 0, 0, 0, 0, 242), trtpn = c(1L, 1L, 1L, 1L, 1L, 1L), trtp = c("TRT A", "TRT A", "TRT A", "TRT A", "TRT A", "TRT A")), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame")) adrs3_all <- adrs4 ggplot((adrs4 %>% filter(trtpn==1)),aes(reorder(subjid,trtedy), trtedy)) + geom_bar(stat="identity", aes(fill=factor(trtp))) + geom_point(data=(adrs3_all %>% filter(trtpn==1)), aes(subjid, ady, colour=avalc, shape=avalc), size=10) + coord_flip() + theme(text=element_text(family="sans")) + scale_color_manual(values = c('darkcyan','brown','darkviolet','red','forestgreen','darkgoldenrod2','black')) + # 用命名向量定义avalc各值对应的形状编码 scale_shape_manual(values = c( "CR" = 17, # 实心上三角 "PR" = 16, # 实心圆 "SD" = 1, # 空心圆 "PD" = 22, # 空心正方形 "On-treatment" = 25, # 空心上三角 "EOT" = 8, # 八角星 "Death" = 4 # 叉号 ), guide = "none") + scale_y_continuous(limits = c(0,600),breaks=seq(0,600,50)) + labs(fill="Treatment", colour="Response", shape="Response", x="Subject ID ", y="Days", title="Swimmers Plot",subtitle = 'All Treated Subjects') + theme(plot.title = element_text(hjust = 0.5), # 修正居中参数,原1.5会导致标题偏移 plot.caption = element_text(size=15, hjust=0.5), legend.text = element_text(size=15)) + theme_classic(base_size = 20)
关键说明
- 形状映射规则:通过命名向量直接指定每个
avalc因子水平对应的形状编码,ggplot会自动完成匹配;你可以根据需求替换为其他形状编码(参考ggplot官方形状编码表) - 替换unicode对象:使用ggplot内置的形状编码(数字形式)替代未定义的
unicode对象,避免报错 - 修正标题居中:将
plot.title的hjust参数从1.5改为0.5,实现标题真正居中
内容的提问来源于stack exchange,提问作者jkatam
相关产品推荐
相关产品推荐

