问题描述
我想对ggplot2图进行一些编辑,但是我被卡住了。
对于标题,我想合并“物质”标签(也就是“酒精”,“香烟”等的一个标题),然后我将顶部的0和1完全删除,因为它们是已经通过图例重新标记,因此是多余的。
我也想将相同形状的标记稍微靠近一点(aka每个三角形应该更靠近另一个三角形,并且与圆圈相同)。这样一来,就可以更容易地判断它们应该组合在一起。
最后,我想删除“颜色”下的图例标记,并使“同时代”一词的颜色变为与图相对应的灰色。这样就不会将它们与形状图例指示器混淆。
我已经尝试过strip.text.x = element_blank()
和其他一些尝试,但是一直遇到错误。谢谢!
这是我创建的图形:
这是我的代码:
ggplot(data = gfrdata,aes(x = factor(model_cont0_lag1),y = est,ymin = lcl,ymax = ucl,color = model_cont0_lag1,shape = model_year0_curr1)) +
geom_pointrange(size = 0.8) +
ylim(-24,20) +
scale_color_manual(values = c(Contemporaneous = "gray60",Lagged = "gray0")) +
labs(color = 'Color',shape = 'Shape',x = ' ',y = 'Percent Difference (95% CI)') +
geom_errorbar(aes(ymin = lcl,ymax = ucl),width = 0.45,cex = 1) +
facet_grid(.~substance+model_year0_curr1,scale = 'free',space = 'free') +
geom_hline(yintercept = 0,linetype = 2) +
theme_classic() +
theme(panel.spacing=unit(0,"lines"),axis.text.x = element_blank(),axis.ticks.x = element_blank(),strip.background = element_blank(),legend.position = "right",legend.direction = "vertical",legend.text = element_text(color = "black"),legend.title = element_text(face = "bold"))```
解决方法
也许这就是您想要的:
- 要仅用
substance
来获得我的方法方面的一个标签,就只能切换到facet_wrap
。 - 要正确获取点范围的顺序,我在
model_year0_curr1
上映射了x
,并在position_dodge
和geom_pointrange
中都使用了geom_errorbar
。 - 使用
position_dodge
可以设置宽度以减小circles
和triangels
之间的间距 - 为了正确显示图例标签的颜色,我使用了
ggtext::element_markdown
,它允许使用一些CSS来样式化图例标签。
使用一些随机示例数据尝试以下操作:
library(ggplot2)
library(ggtext)
set.seed(42)
y <- runif(16,min = -.1,max = .1) * 100
gfrdata <- data.frame(
substance = rep(c("Alcohol","Cigarettes","E - cigarettes","Marijuana"),each = 4),model_year0_curr1 = rep(c("Past 30 Days","Previous Year"),each = 2),model_cont0_lag1 = c("Contemporaneous","Lagged"),est = y,lcl = y - runif(16,max = .05) * 100,ucl = y + runif(16,max = .05) * 100
)
ggplot(data = gfrdata,aes(x = rev(model_year0_curr1),y = est,ymin = lcl,ymax = ucl,color = model_cont0_lag1,shape = model_year0_curr1)) +
geom_pointrange(size = 0.8,position = position_dodge(0.5)) +
ylim(-24,20) +
scale_color_manual(values = c(Contemporaneous = "gray60",Lagged = "gray0"),labels = c(Contemporaneous = "<span style='color: grey60'>Contemporaneous</span>",Lagged = "<span style='color: grey0'>Lagged</span>")) +
labs(color = 'Color',shape = 'Shape',x = ' ',y = 'Percent Difference (95% CI)') +
geom_errorbar(aes(ymin = lcl,ymax = ucl),position = position_dodge(0.5),width = 0.45,cex = 1) +
facet_wrap(~substance,nrow = 1) +
geom_hline(yintercept = 0,linetype = 2) +
theme_classic() +
theme(panel.spacing=unit(0,"lines"),axis.text.x = element_blank(),axis.ticks.x = element_blank(),strip.background = element_blank(),legend.position = "right",legend.direction = "vertical",legend.text = element_markdown(color = "black"),legend.title = element_text(face = "bold"))