在R的ggplot2中修改图例、点样式及坐标轴标签样式
解决方法
核心调整要点
- 在ggplot内直接重命名type:通过
factor(type, labels = c("TLA1", "TLA2", "TLA3", "TLA4"))在映射环节完成重命名,无需修改原始数据框,保证代码可复用性。 - 点形状与类型绑定:将
shape映射到重命名后的type,同时搭配颜色映射,让不同类型的散点区分更清晰。 - x轴刻度标签着色:先匹配每个Tag对应的type颜色,再通过主题设置给刻度标签上色。
完整可复用代码
# 先处理Percentage的格式(替换逗号为点,转换为数值型) MeMeT1A$Percentage <- as.numeric(gsub(",", ".", MeMeT1A$Percentage)) ggplot(MeMeT1A, aes(x = Tag, y = Percentage, shape = factor(type, labels = c("TLA1", "TLA2", "TLA3", "TLA4")), color = factor(type, labels = c("TLA1", "TLA2", "TLA3", "TLA4")))) + geom_point(size = 3) + labs(title = "Top5 Medulla Input Types", x = "Inputneuron", y = "(%) medulla input", shape = "Experimental Condition", color = "Experimental Condition") + # 手动设置点形状和颜色 scale_shape_manual(values = c(15, 16, 17, 18)) + scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9", "#E69F00")) + theme_bw() + geom_hline(yintercept = seq(0, 1, by = 0.1), linetype = "longdash", color = "gray") + # 设置x轴样式,包括刻度颜色 theme( text = element_text(size = 8), axis.text.x = element_text(angle = 45, hjust = 1, color = c("#999999", "#999999", "#E69F00", "#E69F00", "#56B4E9", "#56B4E9", "#E69F00")) )
补充说明
如果Tag的顺序不固定,不想手动写颜色向量,可以用以下代码动态生成对应颜色:
library(dplyr) # 动态获取每个Tag对应的颜色 tag_color <- MeMeT1A %>% distinct(Tag, type) %>% mutate(color = case_when( type == 1 ~ "#999999", type == 2 ~ "#E69F00", type == 3 ~ "#56B4E9", type == 4 ~ "#E69F00" )) %>% pull(color)
之后在theme的axis.text.x里把color参数换成tag_color即可。
内容的提问来源于stack exchange,提问作者Miga
相关产品推荐
相关产品推荐

