Reputation: 7526
I have two separate regression lines in my ggplot, each corresponding to a separate variable. However, the second line corresponding to local
does not extend across the entire graph. Is there a workaround for this or a way to make both ablines extend equally across the area of the graph?
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())
Here is a sample of the data:
> 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")
Upvotes: 5
Views: 6762
Reputation: 17299
Add fullrange = T
to stat_smooth
will make the fit span the full range of the plot:
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())
Upvotes: 14