简体   繁体   中英

ggplot2: Extend stat_smooth regression line to entire x-range of plot area

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")

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM