在ggplot区域外添加文本

时间:2019-08-02 18:14:34

标签: r ggplot2 visualization

我正在尝试使用ggplot2制作组合图。但是我想在我的情节正文之外添加一个文本框排序。我无法将其放置在所需的位置

我已使用网格包创建grob,并将其包含在ggplot代码的注释中。另外,我也将相同的文本放在geom_text中。我如何确保文字在图例下说。以下是我的代码

m <- ggplot() +
  geom_area(data= (ly_vol_ntwk %>%
                     mutate(Wk_end_d = as.factor(Wk_end_d))%>%
                     filter(!is.na(value_new))),
            aes(x = Wk_end_d, y = value_new ,group = variable,fill=variable))+ 
  geom_bar(data = (fcst_act_vol_ntwk %>% 
                     mutate(Wk_end_d = as.factor(Wk_end_d))%>%
                     filter(!is.na(value_new))),
           aes(x = Wk_end_d, y = value_new, group = variable, fill = variable), 
           stat = "identity",position = "dodge", width =0.5)+
  geom_line(data = (var_vol_ntwk %>% 
                      mutate(Wk_end_d = as.factor(Wk_end_d))%>%
                      filter(!is.na(value_new))),
            aes(x = Wk_end_d, y = value_new, 
                group = variable, fill= variable), size = 0.8)+ 
  scale_y_continuous(sec.axis = sec_axis(trans = ~./100000, 
                                         name = "Variance", breaks = waiver(),
                                         labels=function(x) paste0(x,"%")))+ 
  theme_set(theme_bw())+ 
  theme(axis.text.x = element_text(angle=65, vjust=0.5,face = "plain"),
        text = element_text(size=9), legend.position = "bottom", legend.title = element_blank())+ 
  labs(title= "Inbound - Network", x= "Week end date", y = " ")+ 
  scale_fill_manual(values = c("#C5E0B4","#7030A0", "#D9D9D9","#ED7D31","black"))+ 
  geom_text(label = "LW Variance",
            aes(x = 19, y = -1960000),
            check_overlap = TRUE) #annotation_custom(grob = textGrob("LW Variance"), xmin = 18, xmax = 18, ymin = -1030000, ymax = -1030000)+ coord_cartesian(clip = 'off')

我需要在ggplot区域之外获得带有边框的文本框。你能帮我吗?

2 个答案:

答案 0 :(得分:1)

如果要将其放在当前图例的下方,则可以始终添加一个虚拟图例,并将文本作为其名称。一个例子:

<mat-form-field>
  <mat-select placeholder="Rpi" [(value)]="RpiIp">
    <mat-option>Choose</mat-option>
    <mat-option *ngFor='let pi of myRpis'  ngDefaultControl [value]="pi.RPI_IP"
      (click)="getPins()">
      {{pi.LABEL}}
    </mat-option>
  </mat-select>
</mat-form-field>

答案 1 :(得分:0)

您可以使用labs(caption = "text")将文字放置在绘图区域的下方,但不能在绘图上方放置标题。但是,您可以使用字幕labs(subtitle = "text")在顶部显示类似的字幕。

要进一步控制这两个选项的方面,请使用theme(plot.caption = element_text(...), plot.subtitle = element_text(...))。在控制台中输入?element_text,以获取所有用于文本格式设置的选项。

例如:

library(ggplot2)

df <- data.frame(x = rnorm(50), y = rnorm(50))

ggplot(df, aes(x, y)) +
  geom_point() +
  labs(subtitle = "Your text here", caption = "Your text here") +
  theme(plot.caption = element_text(colour = "red", hjust = 0, angle = 15),
        plot.subtitle = element_text(size = 18, face = "bold", hjust = 0.8))

enter image description here