Как уменьшить расстояние между участками при использовании пэчворка

#r #ggplot2 #patchwork

#r #ggplot2 #пэчворк

Вопрос:

Привет всем, я работаю с небольшим фреймом данных, чтобы построить несколько сюжетов ggplot2 . Мой фрейм данных есть df , и я включаю его как dput() в конце. У меня есть сюжеты, и проблема возникает, когда я использую patchwork . Я хочу, чтобы окончательный участок был без пробелов, чтобы линия посередине, которая является осью, могла соединить участки вместе. Вот код:

 library(ggplot2) library(patchwork) library(cowplot) library(ggtext) #Plot 1 G1 lt;- ggplot(df,aes(x=Var1,y=Var2))   geom_line(aes(color=Group,group=Group),size=1)   geom_point(aes(color=Group,group=Group,shape=Group),size=2)   scale_y_continuous(limits = c(0,NA),  sec.axis = dup_axis(name = '',breaks = NULL,labels = NULL))   theme_half_open(12)    background_grid()    theme(  strip.background = element_blank(),  strip.text = element_textbox(  size = 12,  face = 'bold',  color = "white", fill = "#5D729D", box.color = "#4A618C",  halign = 0.5, linetype = 1, r = unit(5, "pt"), width = unit(1, "npc"),  padding = margin(2, 0, 1, 0), margin = margin(3, 3, 3, 3)  )  )   theme(legend.position = 'top',  axis.title = element_text(color='black',face='bold'),  axis.text = element_text(color='black',face='bold'),  legend.text = element_text(color='black',face='bold'),  legend.title = element_text(color='black',face='bold'),  panel.grid = element_blank(),  legend.justification = 'center',  plot.margin = unit(c(0,0,0,0), "cm"),  plot.title = element_text(color='black',  size=12,  face='bold',hjust=0.5),  plot.caption = element_text(face='bold')) #Plot 2 G2 lt;- ggplot(df,aes(x=Var1,y=Var3))   geom_line(aes(color=Group,group=Group),size=1)   geom_point(aes(color=Group,group=Group,shape=Group),size=2)   scale_y_continuous(limits = c(0,NA),position = 'right')   theme_half_open(12)    background_grid()    theme(  strip.background = element_blank(),  strip.text = element_textbox(  size = 12,  face = 'bold',  color = "white", fill = "#5D729D", box.color = "#4A618C",  halign = 0.5, linetype = 1, r = unit(5, "pt"), width = unit(1, "npc"),  padding = margin(2, 0, 1, 0), margin = margin(3, 3, 3, 3)  )  )   theme(legend.position = 'top',  axis.title = element_text(color='black',face='bold'),  axis.text = element_text(color='black',face='bold'),  legend.text = element_text(color='black',face='bold'),  legend.title = element_text(color='black',face='bold'),  panel.grid = element_blank(),  legend.justification = 'center',  plot.margin = unit(c(0,0,0,0), "cm"),  plot.title = element_text(color='black',  size=12,  face='bold',hjust=0.5),  plot.caption = element_text(face='bold')) #Merge plots G3 lt;- G1 G2 plot_layout(guides = 'collect')amp;theme(legend.position = 'top')  

Это результат для G3 :

введите описание изображения здесь

Видно, что участки не полностью соединены, так как между средней линией и вторым участком есть пространство. Как я могу удалить это пространство?

введите описание изображения здесь

Большое спасибо. Следующие данные df :

 #Data df lt;- structure(list(Var1 = c("A", "B", "C", "A", "B", "C"), Group = c("G1",  "G1", "G1", "G2", "G2", "G2"), Var2 = c(1L, 3L, 4L, 8L, 9L, 0L ), Var3 = c(9L, 8L, 4L, 5L, 1L, 1L)), class = "data.frame", row.names = c(NA,  -6L))  

Комментарии:

1. Дайте мне знать, сработает ли мой ответ для вас

Ответ №1:

Вы можете сделать это, вы можете настроить plot_layout(widths = c()) или вы могли бы настроить поля, используя amp; theme(plot.margin = ...) , однако, я не думаю plot.margin , что это сработает в этом случае.

Чтобы внедрить widths в свой участок, вам нужно будет добавить разделительную полосу и использовать widths ее для настройки разделительной полосы так, чтобы участки полностью соединялись вместе

 G3 lt;- G1   plot_spacer()   G2   plot_layout(widths = c(4, -1.1 ,4.5),guides = "collect")amp; theme(legend.position = "top")  

Здесь ширина участка 1 равна 4, ширина разделительного участка -1.1, что позволяет объединить участки вместе, а ширина участка 2-4,5. Я не уверен, почему у участка 2 должна быть большая ширина, чем у участка 1, но два участка выглядят неправильно, когда обе их ширины равны 4.

пример