r - R 中的 mpg 数据集

标签 r ggplot2

我正在尝试找出一种根据传输类型在 geom_point 图上为我的点着色的方法,但在 mpg 数据集中,trans 列对于自动和手动传输有不同的名称。如何将 trans 列中的值重命名为 Auto(自动变速箱)和 Manual(手动变速箱)?我还附上了所需图表的图片以供引用。

这是我的主要情节代码:

data <- mpg
n <- nrow(mpg)
mpg_auto <- subset(mpg, substring(trans[1:n],1,1)=="a")
mpg_manual <- subset(mpg, substring(trans[1:n],1,1)=="m")

mpg$trans <- factor(mpg$trans, levels=c(mpg_auto,mpg_manual),
                labels = c("0","1"))

mpg_select <- subset(mpg, mpg$hwy > 30 & mpg$displ < 3)
mpg_select <- as.data.frame(mpg_select)

gg<-  ggplot(mpg) + aes(x = displ, y = hwy) + 
  geom_point(aes(col = trans))+
  geom_encircle(aes(x = displ, y = hwy), 
            data = mpg_select, 
            color= "darkgreen",
            expand = .05,
            size = 2) + 
  annotate_textp(x = .2, y = .9, size = 15,
             label = "Efficient Vehicle", color = "darkgreen")+
  labs(y = "Hwy MPG",
       x = "Displacement")

  ggMarginal(gg, type= "density", alpha = 0.5,
       groupColour = TRUE, groupFill = TRUE)

Picture of the plot with the above code: https://ibb.co/fGMSXdn

最佳答案

这是重新标记传输的好方法(我创建了一个名为 transmission 的新列,但您也可以轻松地覆盖现有列)。

mpg$transmission = ifelse(substring(mpg$trans, 1, 1) == "a", "automatic", "manual")

现在已经完成了,着色很容易:

gg <- ggplot(mpg, aes(x = displ, y = hwy) + 
  geom_point(aes(color = transmission))+
  labs(y = "Hwy MPG",
       x = "Displacement")

enter image description here

我遗漏了所有非标准 ggplot 内容,因为我不确定它来自哪个包。无论如何,它似乎与您的问题无关,因此您应该能够将其添加回来。

关于r - R 中的 mpg 数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192128/

相关文章:

r - 如何在 R 中的 ggplotly 中更改图例位置

r - R中有连接tapply和round的函数吗?

r - 将函数参数传递给 dplyr 和 ggplot

r - 如何在 R 中使用 pdf 和 mfrow

r - 使用 ggplot 记录计数的时间序列

r - 了解 dnorm 和 geom_density

r - 如何使用抖动的 geom_points 制作 geom_boxplot 异常值 "line up"?

r - 如何标记由 ggplot2 组成的分位数-分位数图的点?

r - 用户从 R 查找 Twitter API 会导致错误 (403)

sql - R RODBC 将数字列表放入 IN() 语句