![](/img/trans.png)
[英]R - customizing legend in ggplot2 to add geom_vline() component
[英]Add vline to existing plot and have it appear in ggplot2 legend?
我有一些數據用於繪制直方圖。 我也有兩組具有一定意義的閾值。
我可以用適當的樣式繪制直方圖和vlines。 但是,我無法讓我的vlines顯示在圖例中。 我相信這樣的東西應該有用,但是傳奇物品不會顯示出來。
df <- data.frame(val=rnorm(300, 75, 10))
cuts1 <- c(43, 70, 90)
cuts2 <- c(46, 79, 86)
ggplot(data=df, aes(x=val)) +
geom_histogram() +
geom_vline(xintercept=cuts1,
linetype=1,
color="red",
labels="Thresholds A",
show_guide=TRUE) +
geom_vline(xintercept=cuts2,
linetype=2,
color="green",
labels="Thresholds B",
show_guide=TRUE)
或者,如果我為剪切構建一個data.frame並進行美學映射,我可以讓我的vlines顯示在圖例中。 不幸的是,這個圖例給了我兩個不同線型疊加在一起的實例:
cuts1 <- data.frame(Thresholds="Thresholds A", vals=c(43, 70, 90))
cuts2 <- data.frame(Thresholds="Thresholds B", vals=cuts2 <- c(46, 79, 86))
ggplot(data=df, aes(x=val)) +
geom_histogram() +
geom_vline(data=cuts1, aes(xintercept=vals, shape=Thresholds),
linetype=1,
color="red",
labels="Thresholds A",
show_guide=TRUE) +
geom_vline(data=cuts2, aes(xintercept=vals, shape=Thresholds),
linetype=2,
color="green",
labels="Thresholds B",
show_guide=TRUE)
所以,最后,我正在尋找的,是最簡單的方法,手動將兩組線添加到繪圖中,然后讓它們在圖例中正確顯示。
訣竅是將閾值數據全部放在同一個數據框中,然后映射美學,而不是設置它們:
cuts <- rbind(cuts1,cuts2)
ggplot(data=df, aes(x=val)) +
geom_histogram() +
geom_vline(data=cuts,
aes(xintercept=vals,
linetype=Thresholds,
colour = Thresholds),
show_guide = TRUE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.