3 回答
TA贡献1770条经验 获得超3个赞
要使用Baptiste的想法,您需要关闭剪辑。但是,当您这样做时,就会得到垃圾。此外,您需要geom_text隐藏图例,并为(选择)2014年的资本支出(Capex),并增加边距为标签留出空间。(或者,您可以调整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))
TA贡献1835条经验 获得超7个赞
这个问题虽然古老,但却是黄金,我为疲倦的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部分只是用于固定下面的轴。
- 3 回答
- 0 关注
- 667 浏览
添加回答
举报