2017-04-20 211 views
1

我在ggplot中有兩條單獨的迴歸直線,每條迴歸直線對應一個單獨的變量。但是,對應於local的第二行不會擴展到整個圖表。有沒有解決這個問題的方法,或者讓這兩個ablines在圖形區域平均延伸的方法?ggplot2:將stat_smooth迴歸直線延伸至繪圖區域的整個x範圍

ggplot(metrics, aes(x=popDensity, y= TPB, color = factor(type))) + geom_point() +theme_minimal() + stat_smooth(method = "lm", se = FALSE) + 
    geom_label_repel(aes(label= rownames(metrics)), size=3, show.legend = FALSE) + 
    theme(axis.title = element_text(family = "Trebuchet MS", color="#666666", face="bold", size=12)) + 
    labs(x = expression(paste("Populatin Density ", km^{2})), y = expression(paste("Rating")))+ 
    theme(legend.position="top", legend.direction="horizontal") + theme(legend.title=element_blank()) 

enter image description here

下面是數據的一個樣本:

> dput(metrics) 
structure(list(popDensity = c(4308, 27812, 4447, 5334, 4662, 
2890, 1689, 481, 4100), TPB = c(2.65, 4.49, 2.37, 2.87, 3.87, 
2.95, 1.18, 1.62, 1.87), type = c("Global", "Global", "Global", 
"Global", "Global", "Global", "Local", "Local", "Local")), .Names = c("popDensity", 
"TPB", "type"), row.names = c("City1", "City2", "City3", "City4", 
"City5", "City6", "City7", "City8", "City9"), class = "data.frame") 

回答

1

添加fullrange = Tstat_smooth會使配合跨度全方位的情節:

ggplot(metrics, aes(x = popDensity, y = TPB, color = factor(type))) + 
    geom_point() + 
    theme_minimal() + 
    stat_smooth(method = "lm", se = FALSE, fullrange = T) + 
    geom_label_repel(aes(label = rownames(metrics)), 
        size = 3, 
        show.legend = FALSE) + 
    theme(axis.title = element_text(
     family = "Trebuchet MS", 
     color = "#666666", 
     face = "bold", 
     size = 12 
    )) + 
    labs(x = expression(paste("Populatin Density ", km^{2})), 
     y = expression(paste("Rating"))) + 
    theme(legend.position = "top", legend.direction = "horizontal") + 
    theme(legend.title = element_blank())