如何在段的开头将标签添加到geom_segment? [英] How to add label to geom_segment at the start of the segment?

查看:40
本文介绍了如何在段的开头将标签添加到geom_segment?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定这很简单,但我无法弄清楚.

I'm sure this is simple but I can't figure it out.

我有以下图表:

library(data.table)
library(magrittr)
library(ggplot2)

cambodia <- 
    data.table(Period = c("Funan", "Chenla/Zhenla","Khmer Empire","Dark Ages of Cambodia"),
               StartDate = c(-500,550,802,1431), 
               EndDate = c(550,802,1431,1863), 
               Color = c("lightblue","lightgreen","lightyellow","pink")) %>%
    extract(order(-StartDate)) %>%
    extract(, Period := factor(Period,levels = Period))

ggplot() +
    geom_segment(data=cambodia, aes(x=StartDate, xend=EndDate, y=Period, yend=Period, color=Color), 
                 linetype=1, size=2) +
    scale_colour_brewer(palette = "Pastel1")+
    xlab("Date")+
    ylab("Ruler")+
    theme_bw() + 
    theme(panel.grid.minor = element_blank(), panel.grid.major =   element_blank()) + 
    theme(aspect.ratio = .2) +
    theme(legend.position="none")

但是我希望标签不在轴上并且在页面上.在该行的左侧或顶部.例如

But I would like the labels to be off the axis and on the page. Either to the left or on top of the middle of the line. E.g.

geom_text的大多数示例都给我gobbledeegook.我似乎无法将它们应用于此处的因子数据.你知道怎么做吗?谢谢

Most of the examples of geom_text give me gobbledeegook. I can't seem to apply them to the factor data I have here. Do you know how to do this? Thank you

推荐答案

ggplot() +
  geom_segment(data=cambodia, aes(x=StartDate, xend=EndDate, y=Period, yend=Period, color=Color), 
               linetype=1, size=2) +
  geom_label(data=cambodia, aes(x=StartDate, y=Period,  label = Period),
             nudge_x = c(-300, -200, -200, -100)) +
  scale_colour_brewer(palette = "Pastel1")+
  xlab("Date")+
  ylab("")+
  theme_bw() + 
  theme(legend.position="none") +
  theme(aspect.ratio = .2) +
  theme(panel.grid.minor = element_blank(), panel.grid.major =   element_blank(),
        axis.line.y = element_blank(), axis.text.y = element_blank(),
        axis.ticks.y = element_blank())

您需要使用 element_blank()删除y轴元素,然后在 geom_label 中使用 nudge_x 参数适当地偏移标签.

You need to use element_blank() to remove the y axis elements and then use nudge_x argument in geom_label to offset the labels appropriately.

这篇关于如何在段的开头将标签添加到geom_segment?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆