R语言 线端点处的打印标签

n8ghc7c1  于 12个月前  发布在  其他
关注(0)|答案(9)|浏览(81)

我有以下数据(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.颜色与系列相同
1.每个系列最后一个数据点的右侧
我注意到baptiste在下面链接的答案中的评论,但是当我尝试修改他的代码(geom_text(aes(label = State, colour = State, x = Inf, y = Capex), hjust = -1))时,文本没有出现。
ggplot2 - annotate outside of plot

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"))

xpszyzbs

xpszyzbs1#

一个较新的解决方案是使用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)

字符串


的数据

azpvetkf

azpvetkf2#

要使用Baptiste的想法,您需要关闭剪裁。但是当您这样做时,您会得到垃圾。此外,您需要隐藏图例,并且对于geom_text,选择Capex for 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))

t3irkdon

t3irkdon3#

我为疲惫的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部分只是固定下面的轴。


的数据

yqlxgs2m

yqlxgs2m4#

有一个新的软件包来解决这个非常流行的问题。{geomtextpath}提供了一些非常灵活的选择直接标签,比“只”标签在最后.
而且,标签会沿着曲线!这可能不符合每个人的口味,但我觉得这是一个非常整洁的外观。

library(geomtextpath)

## end of line
ggplot(temp.dat) +
  geom_textline(aes(
    x = Year, y = Capex, group = State, colour = State, label = State
  ),
  hjust = 1
  ) +
  theme(legend.position = "none")

字符串
x1c 0d1x的数据

## somewhere in the middle
ggplot(temp.dat) +
  geom_textline(aes(
    x = Year, y = Capex, group = State, colour = State, label = State
  ),
  hjust = .7
  ) +
  theme(legend.position = "none")



有很多geom,还有一个基于geom_smooth的预测曲线。(回答用户Mark Neal)

ggplot(temp.dat, aes(x = Year, y = Capex, group = State, colour = State)) +
  geom_line() +
  ## note this is using the current dev version. you currently have to specify method argument, otherwise the disambiguation of some function fails. 
  ## see also https://github.com/AllanCameron/geomtextpath/issues/79) +
  geom_textsmooth(aes(label = State), 
                  lty = 2, 
                  hjust = 1) +
  theme(legend.position = "none")
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

创建于2022-07-12由reprex package(v2.0.1)

wbgh16ku

wbgh16ku5#

我想为标签名称较长的情况添加一个解决方案。在提供的所有解决方案中,标签都在绘图画布内,但如果您有较长的名称,它们将被切断。以下是我解决这个问题的方法:

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"))

字符串


的数据

cmssoen2

cmssoen26#

不确定这是否是最好的方法,但您可以尝试以下方法(使用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))

字符串


的数据

bqujaahr

bqujaahr7#

我来到这个问题,希望直接标记最后一个拟合点的拟合线(例如loess()),而不是最后一个数据点。我最终找到了一种方法来做到这一点,主要基于tidyverse它也应该适用于线性回归和一些mods,所以我把它留给后人。

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))

字符串


的数据

vxbzzdmp

vxbzzdmp8#

你没有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)

字符串
(You如果你保持白色背景,我会想改变黄色。)
x1c 0d1x的数据

ki0zmccv

ki0zmccv9#

还有一个答案中没有提到的选项,我经常使用的是使用所谓的辅助轴技巧,这意味着使用辅助轴或复制轴将直接标签添加到行的末尾。
这种方法的优点是,我们不需要摆弄扩展限制或边距或......为标签腾出空间,因为图表将自动重新调整大小以为轴文本腾出空间,因此即使对于长标签也很好。
对于颜色标签,我使用ggh4x::guide_axis_color作为vanilla ggplot2,官方不支持将颜色向量传递给axis.text.y.right,其他方法,例如使用ggtext需要更多的工作。

library(ggplot2)

# Dataframe of breaks and labels
sec_y <- subset(
  temp.dat,
  Year == max(Year),
  select = c(Capex, State)
) |>
  setNames(c("breaks", "labels"))

ggplot(
  temp.dat,
  aes(x = Year, y = Capex, color = State, group = State)
) +
  geom_line() +
  scale_y_continuous(
    sec.axis = dup_axis(
      breaks = sec_y$breaks,
      labels = sec_y$labels,
      # Add colors
      guide = ggh4x::guide_axis_color(
        color = scales::hue_pal()(nrow(sec_y))
      )
    )
  ) +
  guides(color = "none") +
  # Get rid of secondary axis ticks and title
  theme(
    axis.ticks.y.right = element_blank(),
    axis.title.y.right = element_blank()
  )

字符串


的数据

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

sec_y <- subset(
  temp.dat,
  Year == max(Year),
  select = c(Capex, State)
) |>
  setNames(c("breaks", "labels"))
sec_y <- sec_y[order(sec_y$labels), ]
ggplot(
  temp.dat,
  aes(x = Year, y = Capex, color = State, group = State)
) +
  geom_line() +
  scale_y_continuous(
    sec.axis = dup_axis(
      breaks = sec_y$breaks,
      labels = sec_y$labels,
      guide = ggh4x::guide_axis_color(
        color = scales::hue_pal()(nrow(sec_y))
      )
    )
  ) +
  guides(color = "none") +
  theme(
    axis.ticks.y.right = element_blank(),
    axis.title.y.right = element_blank()
  )


相关问题