這裏創建的元素創建傳說是示例數據集中:在geom_histogram從geom_vline
structure(list(Age = c(6L, 7L, 5L, 6L, 7L, 9L,6L, 7L, 5L, 6L, 7L, 9L,6L, 7L, 5L, 6L, 7L, 9L), Year = c(2011,
2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011)), .Names = c("Age", "Year"), row.names = c(NA, 6L), class = "data.frame")
我想創建一個傳說,將顯示三個組成部分,我在下面我geom_vline命令列表。我讀過的幾個例子在s.overflow,但似乎沒有奏效..
這是我到目前爲止有:
# to create standard errors and mean lines to plot on histogram
se <- function(x) sqrt(var(x)/length(x))
se_11 <- se(Age_2011$Age)
mean_11 <- mean(Age_2011$Age)
se_11_plus <- mean_11 + se_11
se_11_minus <- mean_11 - se_11
#plot
p11_age <- ggplot(Age_2011, aes(x=Age))+
geom_histogram(aes(y=(..count..)/sum(..count..)), binwidth=1, origin=-.5, fill="white", color="black", show_guide=TRUE)+
scale_y_continuous(labels=percent_format(), name="Frequency (%)")+ ## plotting in percent frequency
xlab("Age (years)")+
scale_x_continuous(limits=c(1,45), breaks=seq(1,45,1))+
scale_colour_discrete(name="Units", guide="legend")+ #attempting to create legend
# vertical lines for mean and standard errors
geom_vline(aes(xintercept=mean(Age_2011$Age), na.rm=T), color="red", linetype="dashed", size=1, show_guide=TRUE)+
geom_vline(aes(xintercept=se_11_plus), color ="blue", show_guide=TRUE)+
geom_vline(aes(xintercept=se_11_minus), color="blue", show_guide=TRUE)+
# creating custom legends using guides
scale_linetype_manual(name="test", labels =c("median", "test", "test2"), values = c("median"=1, "test"=2, "test3"=3))+
theme(legend.key=element_rect(fill="white", color ="white"))+
theme(legend.background=element_blank())+
guides(colour=guide_legend(override.aes=list(linetype=0)), fill=guide_legend(override.aes=list(linetype=0)),
shape=guide_legend(override.aes=list(linetype=0)),
linetype=guide_legend())+
#title and background
ggtitle("Age Frequency Histogram of 2011 Catch")+
theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.background=element_rect(colour="black", fill="white"))
所有geom_vlines的秀,但是我無法弄清楚如何當真的只有一個直方圖「系列」,並且我想要在圖例中是垂直線時獲得圖例。
任何幫助表示讚賞。謝謝
你似乎想要'中位數','測試'和'test2'的線型,但我沒有看到其他的參考。此外,只有2種顏色:平均值爲紅色,半值爲藍色。我不清楚你在試圖完成什麼>> – jlhoward
@jlhoward,中位數,測試和測試2應該是我想要在圖例中顯示的3條垂直線的填充名稱。簡單地說,我想要一個有三行標題爲中位數,測試和測試2的傳說。你上面看到的是我試圖做到這一點,然而,顯然不是。這說明了嗎? – Elizabeth
查看jlhoward的解決方案:http://stackoverflow.com/questions/24148423/r-ggplot-with-two-series-points-and-errorbars-with-legends/24149621#24149621 – Vlo