3 回答

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個贊
要使用Baptiste的想法,您需要關(guān)閉剪輯。但是,當(dāng)您這樣做時,就會得到垃圾。此外,您需要geom_text隱藏圖例,并為(選擇)2014年的資本支出(Capex),并增加邊距為標(biāo)簽留出空間。(或者,您可以調(diào)整hjust參數(shù)以在打印面板內(nèi)移動標(biāo)簽。)類似以下內(nèi)容:
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)
在此處輸入圖片說明
但是,這是最適合的情節(jié)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))
在此處輸入圖片說明
編輯 要增加端點(diǎn)和標(biāo)簽之間的間距,請執(zhí)行以下操作:
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貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個贊
這個問題雖然古老,但卻是黃金,我為疲倦的ggplot人士提供了另一個答案。
該解決方案的原理可以相當(dāng)普遍地應(yīng)用。
Plot_df <-
temp.dat %>% mutate_if(is.factor, as.character) %>% # Who has time for factors..
mutate(Year = as.numeric(Year))
現(xiàn)在,我們可以子集數(shù)據(jù)了
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 關(guān)注
- 721 瀏覽
添加回答
舉報(bào)