代码之家  ›  专栏  ›  技术社区  ›  Jill Sellum

点图的ggplot版本

  •  1
  • Jill Sellum  · 技术社区  · 7 年前

    好奇如何使用ggplot或plotly库函数绘制此点图。同时在单个点上标记mpg值。

    # Dotplot: Grouped Sorted and Colored
    # Sort by mpg, group and color by cylinder 
    x <- mtcars[order(mtcars$mpg),] # sort by mpg
    x$cyl <- factor(x$cyl) # it must be a factor
    x$color[x$cyl==4] <- "red"
    x$color[x$cyl==6] <- "blue"
    x$color[x$cyl==8] <- "darkgreen"    
    dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl,
             main="Gas Milage for Car Models\ngrouped by cylinder",
             xlab="Miles Per Gallon", gcolor="black", color=x$color)
    

    enter image description here

    2 回复  |  直到 7 年前
        1
  •  5
  •   zacdav    7 年前

    我们曾经 factor() 对于色彩的美学,使其变得离散/ 当切面以实现此外观时,您需要指定 "free_y" scale space

    基础

    library(tidyverse)
    mtcars2 = rownames_to_column(mtcars, "car")
    ggplot(mtcars2, aes(x = mpg, y = factor(car), color = factor(cyl))) + 
      geom_point(shape = 1) + 
      facet_grid(cyl ~ ., scales = "free_y", space = "free_y") + 
      theme_bw() + 
      theme(panel.grid = element_blank(),
            panel.grid.major.y = element_line(size=.1, color="grey90"),
            legend.position = "none") +
      ggtitle("Gas Milage for Car Models\ngrouped by cylinder") + 
      xlab("Miles Per Gallon") +
      ylab("")
    

    enter image description here


    添加文本

    ggplot(mtcars2, aes(x = mpg, y = factor(car), color = factor(cyl))) + 
      geom_point(shape = 1) + 
      geom_text(aes(label = mpg), colour = "grey40", size = 3, hjust = -0.3) + 
      facet_grid(cyl ~ ., scales = "free_y", space = "free_y") + 
      theme_bw() + 
      theme(panel.grid = element_blank(),
            panel.grid.major.y = element_line(size=.1, color="grey90"),
            legend.position = "none") +
      ggtitle("Gas Milage for Car Models\ngrouped by cylinder") + 
      xlab("Miles Per Gallon") +
      ylab("")
    

    enter image description here

    你可以使用 geom_label geom_text 在这里效果很好。

        2
  •  4
  •   Marius    7 年前

    forcats :

    library(tidyverse)
    library(forcats)
    mtcars2 = rownames_to_column(mtcars, "car") %>%
        mutate(car_ordered = fct_reorder2(car, cyl, mpg, .desc = FALSE))
    
    ggplot(mtcars2, aes(x = mpg, y = car_ordered, color = factor(cyl))) + 
        geom_point(shape = 1) + 
        geom_text(aes(label = mpg), colour = "grey40", size = 3, hjust = -0.3) + 
        facet_grid(cyl ~ ., scales = "free_y", space = "free_y") + 
        theme_bw() + 
        theme(panel.grid = element_blank(),
              panel.grid.major.y = element_line(size=.1, color="grey90"),
              legend.position = "none") +
        ggtitle("Gas Milage for Car Models\ngrouped by cylinder") + 
        xlab("Miles Per Gallon") +
        ylab("")
    

    enter image description here