在行尾绘制标签


76

我有以下数据(temp.dat有关完整数据,请参见结尾注释)

   Year State     Capex
1  2003   VIC  5.356415
2  2004   VIC  5.765232
3  2005   VIC  5.247276
4  2006   VIC  5.579882
5  2007   VIC  5.142464
...

我可以生成以下图表:

ggplot(temp.dat) + 
  geom_line(aes(x = Year, y = Capex, group = State, colour = State))

在此处输入图片说明

我希望标签不是传说,而是

  1. 颜色与系列相同
  2. 每个系列的最后一个数据点的右侧

我在以下链接的答案中注意到baptiste的评论,但是当我尝试修改他的代码(geom_text(aes(label = State, colour = State, x = Inf, y = Capex), hjust = -1))时,文本不会出现。

ggplot2-在情节之外进行注释

temp.dat <- structure(list(Year = c("2003", "2004", "2005", "2006", "2007", 
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2003", 
"2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", 
"2012", "2013", "2014", "2003", "2004", "2005", "2006", "2007", 
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2003", 
"2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", 
"2012", "2013", "2014"), State = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("VIC", 
"NSW", "QLD", "WA"), class = "factor"), Capex = c(5.35641472365348, 
5.76523240652641, 5.24727577535625, 5.57988239709746, 5.14246402568366, 
4.96786288162828, 5.493190785287, 6.08500616799372, 6.5092228474591, 
7.03813541623157, 8.34736513875897, 9.04992300432169, 7.15830329914056, 
7.21247045701994, 7.81373928617117, 7.76610217197542, 7.9744994967006, 
7.93734452080786, 8.29289899132255, 7.85222269563982, 8.12683746325074, 
8.61903784301649, 9.7904327253813, 9.75021175267288, 8.2950673974226, 
6.6272705639724, 6.50170524635367, 6.15609626379471, 6.43799637295979, 
6.9869551384028, 8.36305663640294, 8.31382617231745, 8.65409824343971, 
9.70529678167458, 11.3102788081848, 11.8696420977237, 6.77937303542605, 
5.51242844820827, 5.35789621712839, 4.38699327451101, 4.4925792218211, 
4.29934654081527, 4.54639175257732, 4.70040615159951, 5.04056109514957, 
5.49921208937735, 5.96590909090909, 6.18700407463007)), class = "data.frame", row.names = c(NA, 
-48L), .Names = c("Year", "State", "Capex"))

我只想用想要绘制的数据创建一个单独的数据框,geom_text(data = temp.dat[cumsum(table(temp.dat$State)), ], aes(label = State, colour = State, x = Year, y = Capex))但是可能会有更多的gg方式做这些事
rawr 2015年

Answers:


89

要使用Baptiste的想法,您需要关闭剪辑。但是,当您这样做时,就会得到垃圾。此外,您需要geom_text隐藏图例,并为(选择)2014年的资本支出,并增加页边距,为标签留出空间。(或者,您可以调整hjust参数以在打印面板内移动标签。)类似以下内容:

library(ggplot2)
library(grid)

p = ggplot(temp.dat) + 
  geom_line(aes(x = Year, y = Capex, group = State, colour = State)) + 
  geom_text(data = subset(temp.dat, Year == "2014"), aes(label = State, colour = State, x = Inf, y = Capex), hjust = -.1) +
  scale_colour_discrete(guide = 'none')  +    
  theme(plot.margin = unit(c(1,3,1,1), "lines")) 

# Code to turn off clipping
gt <- ggplotGrob(p)
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

在此处输入图片说明

但是,这是最适合的情节directlabels

library(ggplot2)
library(directlabels)

ggplot(temp.dat, aes(x = Year, y = Capex, group = State, colour = State)) + 
  geom_line() +
  scale_colour_discrete(guide = 'none') +
  scale_x_discrete(expand=c(0, 1)) +
  geom_dl(aes(label = State), method = list(dl.combine("first.points", "last.points")), cex = 0.8) 

在此处输入图片说明

编辑 要增加端点和标签之间的间距,请执行以下操作:

ggplot(temp.dat, aes(x = Year, y = Capex, group = State, colour = State)) + 
  geom_line() +
  scale_colour_discrete(guide = 'none') +
  scale_x_discrete(expand=c(0, 1)) +
  geom_dl(aes(label = State), method = list(dl.trans(x = x + 0.2), "last.points", cex = 0.8)) +
  geom_dl(aes(label = State), method = list(dl.trans(x = x - 0.2), "first.points", cex = 0.8)) 

4
不知道directlabels包。我在文档中看不到手动增加端点和文本标签之间的水平空间的方法。最好的方法是什么?

我添加了一个编辑。请参阅常见问题解答(第5号),网址
Sandy Muspratt,2015年

尝试安装软件包:package ‘directlabels’ is not available (for R version 3.3.2)。我也找不到该软件包的FAQ网站。它还活着吗?
MERose

@MERose嗯。我不确定发生了什么。该链接仍然有效。第一页上是“常见问题”。而且我刚刚检查过cran-directlabels可用。
桑迪·穆斯普拉特

@slhck,似乎尚未安装。您是否尝试安装quadprog
桑迪·穆斯普拉特

74

一种较新的解决方案是使用ggrepel

library(ggplot2)
library(ggrepel)
library(dplyr)

temp.dat %>%
  mutate(label = if_else(Year == max(Year), as.character(State), NA_character_)) %>%
  ggplot(aes(x = Year, y = Capex, group = State, colour = State)) + 
  geom_line() + 
  geom_label_repel(aes(label = label),
                  nudge_x = 1,
                  na.rm = TRUE)

在此处输入图片说明


7
完美-但是我添加了“ scale_color_discrete(guide = FALSE)”,从图表的外部删除了现在不必要的图例(节省了一些重要的屏幕空间)
juhariis

您好,您可以将其扩展为这种情况:stackoverflow.com/questions/48487713/… 吗?
Hercules Apergis

25

这个问题虽然古老,但却是黄金,我为疲倦的ggplot人士提供了另一个答案。

该解决方案的原理可以相当普遍地应用。

Plot_df <- 
  temp.dat %>% mutate_if(is.factor, as.character) %>%  # Who has time for factors..
  mutate(Year = as.numeric(Year))

现在,我们可以子集数据了

ggplot() + 
geom_line(data = Plot_df, aes(Year, Capex, color = State)) +
geom_text(data = Plot_df %>% filter(Year == last(Year)), aes(label = State, 
                                                           x = Year + 0.5, 
                                                           y = Capex, 
                                                           color = State)) + 
          guides(color = FALSE) + theme_bw() + 
          scale_x_continuous(breaks = scales::pretty_breaks(10))

最后的pretty_breaks部分只是用于固定下面的轴。

在此处输入图片说明


8

不确定这是否是最好的方法,但是您可以尝试以下操作(稍微尝试一下以xlim正确设置限制):

library(dplyr)
lab <- tapply(temp.dat$Capex, temp.dat$State, last)
ggplot(temp.dat) + 
    geom_line(aes(x = Year, y = Capex, group = State, colour = State)) +
    scale_color_discrete(guide = FALSE) +
    geom_text(aes(label = names(lab), x = 12, colour = names(lab), y = c(lab), hjust = -.02))

在此处输入图片说明


2
这将产生一条错误消息:“错误:美学必须为长度1或与数据(48)相同:x,y,标签,正好”
invictus

3

您没有100%模仿@Baptiste的解决方案。您需要使用annotation_custom并遍历所有Capex

library(ggplot2)
library(dplyr)
library(grid)

temp.dat <- structure(list(Year = c("2003", "2004", "2005", "2006", "2007", 
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2003", 
"2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", 
"2012", "2013", "2014", "2003", "2004", "2005", "2006", "2007", 
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2003", 
"2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", 
"2012", "2013", "2014"), State = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("VIC", 
"NSW", "QLD", "WA"), class = "factor"), Capex = c(5.35641472365348, 
5.76523240652641, 5.24727577535625, 5.57988239709746, 5.14246402568366, 
4.96786288162828, 5.493190785287, 6.08500616799372, 6.5092228474591, 
7.03813541623157, 8.34736513875897, 9.04992300432169, 7.15830329914056, 
7.21247045701994, 7.81373928617117, 7.76610217197542, 7.9744994967006, 
7.93734452080786, 8.29289899132255, 7.85222269563982, 8.12683746325074, 
8.61903784301649, 9.7904327253813, 9.75021175267288, 8.2950673974226, 
6.6272705639724, 6.50170524635367, 6.15609626379471, 6.43799637295979, 
6.9869551384028, 8.36305663640294, 8.31382617231745, 8.65409824343971, 
9.70529678167458, 11.3102788081848, 11.8696420977237, 6.77937303542605, 
5.51242844820827, 5.35789621712839, 4.38699327451101, 4.4925792218211, 
4.29934654081527, 4.54639175257732, 4.70040615159951, 5.04056109514957, 
5.49921208937735, 5.96590909090909, 6.18700407463007)), class = "data.frame", row.names = c(NA, 
-48L), .Names = c("Year", "State", "Capex"))

temp.dat$Year <- factor(temp.dat$Year)

color <- c("#8DD3C7", "#FFFFB3", "#BEBADA", "#FB8072")

gg <- ggplot(temp.dat) 
gg <- gg + geom_line(aes(x=Year, y=Capex, group=State, colour=State))
gg <- gg + scale_color_manual(values=color)
gg <- gg + labs(x=NULL)
gg <- gg + theme_bw()
gg <- gg + theme(legend.position="none")

states <- temp.dat %>% filter(Year==2014)

for (i in 1:nrow(states))  {
  print(states$Capex[i])
  print(states$Year[i])
  gg <- gg + annotation_custom(
    grob=textGrob(label=states$State[i], 
                    hjust=0, gp=gpar(cex=0.75, col=color[i])),
    ymin=states$Capex[i],
    ymax=states$Capex[i],
    xmin=states$Year[i],
    xmax=states$Year[i])
}    

gt <- ggplot_gtable(ggplot_build(gg))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.newpage()
grid.draw(gt)

(如果要保持白色背景,则要更改黄色。)

在此处输入图片说明


3

我想为标签名称较长的情况添加解决方案。在提供的所有解决方案中,标签都位于绘图画布中,但是如果名称较长,则会被剪掉。这是我解决该问题的方法:

library(tidyverse)

# Make the "State" variable have longer levels
temp.dat <- temp.dat %>% 
    mutate(State = paste0(State, '-a-long-string'))

ggplot(temp.dat, aes(x = Year, y = Capex, color = State, group = State)) + 
    geom_line() +
    # Add labels at the end of the line
    geom_text(data = filter(temp.dat, Year == max(Year)),
              aes(label = State),
              hjust = 0, nudge_x = 0.1) +
    # Allow labels to bleed past the canvas boundaries
    coord_cartesian(clip = 'off') +
    # Remove legend & adjust margins to give more space for labels
    # Remember, the margins are t-r-b-l
    theme(legend.position = 'none',
          plot.margin = margin(0.1, 2.6, 0.1, 0.1, "cm")) 

在此处输入图片说明


如果我只想在较低的一点上放置一些标记或X或坐标(如果在这种情况下,如何在WA-a-long-(2008,5)中放置一些标签),请您帮助我,字符串吗?我会感谢您的回复!
Stackuser

在我的解决方案中,我过滤数据以选择标签所需的确切x和y坐标。由于我希望它们位于行尾,因此我data = filter(temp.dat, Year == max(Year))geom_text()通话中使用了它们。在您的情况下,您可以将过滤器更改为data = filter(temp.dat, Year == 2008, State = "WA"),这将在2008年的x位置仅给您“ WA”标签,并且您可以通过nudge_ygeom_text()
jhelvy

我不认为这是一种改进,因为硬边距设置不切实际。按照我下面的解决方案:temp.dat <-temp.dat%>%mutate(State = paste0(State,'-a-long-string'))Plot_df <-temp.dat%>%mutate_if(is.factor,as .character)%>%mutate(年份= as.numeric(年份))ggplot()+ geom_line(数据= Plot_df,aes(年份,Capex,颜色=状态))+ geom_text(data = Plot_df%>%filter(年份) == last(Year)),aes(label = State,x = Year + 3,y = Capex,color = State),hjust = 1)+指南(color = FALSE)+ theme_bw()+ scale_x_continuous(breaks =刻度) :: pretty_breaks(10))
尼克

不太确定是什么因素使硬设置边距比硬设置比例限制更不实用。排名靠前的解决方案可修改地块边距。我看到的解决方案与您的解决方案之间的最大区别是,在我的解决方案中,x轴在最后一个数据点处停止,而在您的解决方案中,x轴将根据需要继续延伸,以使标签名称适合没有数据的绘图边界内点。
jhelvy

@jhelvy两件事。首先,硬性设置边距并不比增加x边距简单(一个输入-3年,这是直观而简单的。边距是4个输入且不直观)。到最后一点,您需要扩展图形的x轴-否则,您的名称将超出解决方案中的主题(正是您所不想要的)。在我的解决方案中-名称仍然在您的主题之内,您的主题不在您的范围之内。当然那不是理想的。评分最高的解决方案已过时(此处比其他解决方案要麻烦得多),并且名称也超出了主题选择范围。
尼克

1

我遇到了这个问题,希望loess()在最后一个拟合点而不是最后一个数据点处直接标记一条拟合线(例如)。我最终设计出了一种方法,主要是基于tidyverse。它也可以用于带有一些mod的线性回归,因此我将其保留给后代。

library(tidyverse)

temp.dat$Year <- as.numeric(temp.dat$Year)
temp.dat$State <- as.character(temp.dat$State)

#example of loess for multiple models
#https://stackoverflow.com/a/55127487/4927395

models <- temp.dat %>%
  tidyr::nest(-State) %>%
  dplyr::mutate(
    # Perform loess calculation on each CpG group
    m = purrr::map(data, loess,
                   formula = Capex ~ Year, span = .75),
    # Retrieve the fitted values from each model
    fitted = purrr::map(m, `[[`, "fitted")
  )

# Apply fitted y's as a new column
results <- models %>%
  dplyr::select(-m) %>%
  tidyr::unnest()

#find final x values for each group
my_last_points <- results %>% group_by(State) %>% summarise(Year = max(Year, na.rm=TRUE))

#Join dataframe of predictions to group labels
my_last_points$pred_y <- left_join(my_last_points, results)

# Plot with loess line for each group
ggplot(results, aes(x = Year, y = Capex, group = State, colour = State)) +
  geom_line(alpha = I(7/10), color="grey", show.legend=F) +
  #stat_smooth(size=2, span=0.3, se=F, show_guide=F)
  geom_point(size=1) +
  geom_smooth(se=FALSE)+
  geom_text(data = my_last_points, aes(x=Year+0.5, y=pred_y$fitted, label = State))

direct_label

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.